python study notes the next day

Comparison (i.e. relational) operators

The comparison operators in python are as follows:

Operator description Example
== Check whether the values ​​of the two operands are equal, if so, the condition becomes true If a=3, b=3, then (a == b) is true.
!= Check whether the values ​​of the two operands are equal, if the values ​​are not equal, the condition becomes true. If a=1, b=3, then (al=b) is true.
<> Check whether the values ​​of the two operands are equal, if the values ​​are not equal, the condition becomes true. Such as a=1, b=3 (a <> b) is true. This is similar to the = operator
> Check whether the value of the left operand is greater than the value of the right operand, if it is, the condition is true. If a=7, b=3, then (a> b) is true.
< Check if the value of the left operand is less than the value of the right operand, if it is, the condition is true. If a=7, b=3, then (a<b) is false.

Logical Operators

Insert picture description here

Condition test

Check for equality (==)

Use'==' to judge equality

a='bmw'
b='bmw'
print(a==b)#输出结果:true
#考虑字符串大小写进行相等判断
first_name='Zhou'
last_name='zhou'
print(first_name==last_name)#输出结果:false
print(first_name.lower()==last_name.lower())#输出结果:true
Check if it is not equal (!=)
first_name='Zhou'
last_name='zhou'
print(first_name!=last_name)#输出结果:true
Check multiple conditions (and, or)
goodNews=1
badNews=0
women=1
men=1
#用and将多个条件连接在一起,它们是&&(且)的关系,必须每个条件都符合,才返回true
print(goodNews==badNews and women==men)#输出结果:False
#用or将多个条件连接在一起,它们是||(或)的关系,只要有一个条件符合,就返回true
print(goodNews==badNews or women==men)#输出结果:True
Check whether a specific value is included and not included in the list (in, not in)
#in:检查特定值是否包含在列表中
print('pear' in fruit)#输出结果:True
#not in:检查特定值是否不包含在列表中
print('tomato' not in fruit)#输出结果:True

If statement

Simple if statement

The if statement is used to make judgments, and its format is as follows:
if conditional_test:
do something

a=4
if a==4:
    print('a的值是4')#条件成立:输出

if-else statement

The if-else statement block is similar to a simple if statement, but the else statement allows you to specify what to do if the conditional test fails

age=17
if age<18:
    print("你太小了,不能进来!")
else:
    print("进来吧,这里需要你!")
#输出结果:你太小了,不能进来!    

if-elif-else structure

age=5
if age<4:
    print("你不用付钱")
elif age<8:
    print("收你半价")
else:
    print("拿钱来")
#输出结果:收你半价    

User output (input function) and While loop

The function input() pauses the program and waits for the user to input some text. After getting user input, Python stores it in a variable for your convenience.
The function input() accepts a parameter (this parameter can be any string): the prompt or description to be displayed to the user so that the user knows what to do.

str='please open the widow! \n what the air temperature is:'
tem=input(str)
print("The air temperature is "+tem) 
#通过控制台输入的值进行赋值的变量的类型是字符串,可以通过int()将其转换为数字类型

 

while loop

The for loop is used to have a code block for each element in the collection, while the while loop runs continuously until the specified conditions are not met

#while循环的简单使用
current_number=1
while current_number<5:
    print(current_number)
    current_number+=1
#退出循环
myNumber=23
message='你能想出我心中的数字吗?\n你输入数字:'
temp=12
while temp!=myNumber:
    temp=int(input(message))
    if temp==myNumber:
        print("你是我心中的蛔虫!")
    elif temp>myNumber:
        print("输入大了")
    else:
        print("输入小了")
#使用标志
active=True
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
while active:
    message=input(prompt)
    if message=='quit':
        active=False
    else:
        print()
#使用break

while True:
    message=input(prompt)
    if message=='quit':
        break
    else:
        print()

#在循环中使用continue
current_number=0
while current_number<10:
    current_number+=1
    if(current_number%2==0):
       continue
    print(current_number)

function

A function is a named block of code, used to complete specific tasks.
A function is a program segment that is reused. They allow you to give a block of statements a name, and then you can use that name to run the block of statements as many times as you want anywhere in your program. This is called the calling function. We have used many built-in functions, such as len and range.

Function definition

The function is defined by the def keyword. The def keyword is followed by the identifier name of a function, and then a pair of parentheses. Some variable names can be included in the parentheses, and the line ends with a colon. Next is a block of statements, which are the body of the function.

def greet_user():
     print("Hello!")
greet_user()#调用函数输出:Hello!
global keyword

In python, the variables defined in the function are local variables, and the scope of action is only in the function body. If you want the variables inside the function to act globally, you need to use the global keyword.

def fun(x):
 global a
 return a + x
a = 2
print(fun(3))#输出结果:5
a = 5
print(fun(3))
print("--------")#输出结果:8
Pass information to the function

Actual parameters: when calling a function, the variable parameters passed in in parentheses.
Formal parameters: A piece of information that a function needs to complete its work is called a formal parameter. Formal parameters are divided into positional parameters, default parameters, variable parameters, and keyword parameters.

def full_name(fi_name,la_name):#这里的fi_name,la_name就是形参
    return fi_name.title()+la_name.title()
first_name="zhou"
last_name="yi"
print(full_name(first_name,last_name))#这里的first_name,last_name就是实参
#输出结果:ZhouYi

Prohibited function modification list

To pass a copy of the list to the function, you can do this as follows:
function_name(list_name[:])

-Positional parameters: formal parameters and actual parameters must be consistent, it is best to pass parameters according to the position, if the position does not correspond, specify the description

def info(name,age):
    print("姓名:"+name+" 年龄:"+age)
username='joy'
age='18'
info(username,age)
info(age=age,name=username)
#输出结果都为:姓名:joy 年龄:18

-Default parameters: formal parameters and actual parameters can be inconsistent, if you do not want to use the default parameters, you can specify when calling the function (when calling the function, if the default parameter value is not passed in, it will be considered as the default value)

def mainFood(food1="米饭",food2="白菜"):
    print("我的主食有"+food1+"和"+food2)
mainFood("番薯","土豆")#输出结果:我的主食有番薯和土豆
mainFood("番薯")#输出结果:我的主食有番薯和白菜
mainFood()#输出结果:我的主食有米饭和白菜

-Variable parameter
fun(*a):,*a represents a variable parameter, a is a tuple data type

def sum(*a):
    print(*a)#输出结果:1,2,3
    print(a)#输出结果:(1,2,3)
    sum=0
    for ele in a:
        sum+=ele
    return sum #使用return语句将值返回到调用函数的代码行

print(sum(1,2,3))#输出结果:6

-Keyword parameters
Keyword parameters are closely related to function calls. Function calls use keyword parameters to determine the value of the passed in parameter.
The use of keyword parameters allows the order of the parameters in the function call to be inconsistent with the declaration, because the Python interpreter can match the parameter value with the parameter name.
**k stands for variable parameters (parameters are key-value pairs), k stands for the dictionary composed of these variable parameters

# **k 代表关键字参数,可以传入任意多个key-value,是一个字典
def getInfo(name,age,**k):
    print("名字是"+name+" 年龄是"+age)
    print(k)#输出:{'a': 2, 'b': 3}
getInfo('joy',age,a=2,b=3)#a=2,b=3就代表关键实参

Built-in functions in python (partial)

sort() function

sorted is used to sort collections (here collection is a general term for iterable objects, they can be lists, dictionaries, sets, or even strings), and it is very powerful.
sorted (iterable, cmp, key, reverse)
parameters: iterable can be a list or iterator;
cmp is a comparison function with two parameters;
key is a function with one parameter;
reverse is False or True;
pre-knowledge**: what Is a Lamda expression** (in python)

#ambda表达式是Python中一类特殊的定义函数的形式,使用它可以定义一个匿名函数
la1=lambda x:x**2
print(la1(2))#输出结果:4
#上面的lamda表达式等价于下面
def la2 (x):
    return x**2
print(la2(3))#输出结果:9

Sorted usage example:
sort the list


#对列表排序,返回的对象不会改变原列表
list1=[3,2,4,1,0]
list2=sorted(list1)
print(list2)#输出结果:[0, 1, 2, 3, 4]
print(list1)#输出结果:[3, 2, 4, 1, 0]

#根据自定义规则来排序,使用参数:key
info=['joy','mary','lily','smith']
#根据字符串的长度进行排序
print(sorted(info,key=lambda x:len(x)))#输出结果:['joy', 'mary', 'lily', 'smith']

#sorted 也可以根据多个字段来排序
favorite_fruit=["apple","pear","watermelon","grape"]
#先根据字符串长度排序,后根据字符串首字母的Ascll码进行排序
print(sorted(favorite_fruit,key=lambda x:(len(x),x)))#输出结果:['pear', 'apple', 'grape', 'watermelon']

** Sort according to custom rules and sort the list of tuples **

tuple_list=[('joy',18),('tom',20),('mary',15)]
print(sorted(tuple_list,key=lambda x:x[1],reverse=False))#输出结果:[('mary', 15), ('joy', 18), ('tom', 20)]
print(sorted(tuple_list,key=lambda x:x[1],reverse=True))#输出结果:[('tom', 20), ('joy', 18), ('mary', 15)]

Sorting dictionaries
sort is a method of lists, not suitable for dictionaries, so use the sorted
1.sorted function to sort dictionaries by key/value.
Let’s first introduce the sorted function, sorted(iterable,key,reverse), sorted There are three parameters: iterable, key, and reverse.
Among them, iterable represents objects that can be iterated, such as dict.items(), dict.keys(), etc., key is a function used to select elements to be compared, and reverse is used to specify whether the sorting is in reverse order or order, reverse =true is the reverse order, reverse=false is the order, the default is reverse=false

scores = {
    
    'A':80, 'C':90, 'B':60}
sorted(scores.values()) # 输出 [60,80,90]
sorted(scores.keys())  # 输出 ['A', 'B', 'C']

2. Sort and return the sorted dictionary
A way of using labmda expressions, x[0] is sorted according to key, and x[1] is sorted according to value

dict1={
    
    'a':2,'e':3,'f':8,'d':4}
list1= sorted(dict1.items(),key=lambda x:x[1])
print(list1)
#输出:[('a', 2), ('e', 3), ('d', 4), ('f', 8)]
dict1={
    
    'a':2,'e':3,'f':8,'d':4}
list1= sorted(dict1.items(),key=lambda x:x[0])
print(list1)
#输出:[('a', 2), ('d', 4), ('e', 3), ('f', 8)]

Module

Provides a method in Python to obtain definitions from files, and use them in an interactive instance of a script or interpreter. Such files are called modules;

  • The definition in the module can be imported into another module or the main module (the variable set that can be called when the script is executed is at the highest level and is in calculator mode)
  • Modules are files that include Python definitions and declarations. The file name is the module name plus the .py suffix.
  • Module module name (as a string) may be the global variable name to give
  • Modules are mainly divided into built-in modules, three-party modules and custom modules
    module1.py
import math
Pi=math.pi
def make_pizza(size,*toppings):
    print("make a "+str(size)+"-inch pizza with the following toppings:")
    for topping in  toppings:
        print("-"+topping)

module2.py

import module1#导入模块
from  module1 import make_pizza#导入模块中的函数
#或者 import module1.make_pizza
import sys#导入模块
print(module1.Pi)#输出结果:3.141592653589793
make_pizza(20,"盐","辣椒")
for i in sys.argv:
    print(i) #输出结果:D:/zhouyi/pythonStudy/basics/secondDay/module2.py

Guess you like

Origin blog.csdn.net/qq_44788518/article/details/108558466