【0731 | Day 5】Python基础(三)
一、占位符
#一般字符串连接/普通形式 name = 'Adela' age = str(22) print('My name is '+ name+ ','+ "and I'm "+ age+ ' years old'+ '.') #My name is Adela,and I'm 22 years old.
#占位符 name = 'Adela' age = 22 print("My name is %s,and I'm %d yeas old." % (name, age)) #My name is Adela,and I'm 22 yeas old.
注意:%s --> 针对所有数据类型;%d -->仅针对数字类型
二、format格式化(不推荐)
name = 'Adela' age = 22 print("Hello, {}.I am {}.".format(name, age)) name = 'Adela' age = 22 print("Hello, {1}.I am {0}.".format(age, name)) name = 'Adela' age = 22 print("Hello, {name}.I am {age}.".format(name=name, age=age)) #Hello, Adela.I am 22. #Hello, Adela.I am 22. #Hello, Adela.I am 22.
三、f-string格式化(推荐)
name = 'Adela' age = 22 print(f'Hello, {name}.I am {age}.') print(f'{name*5}') #Hello, Adela.I am 22. #AdelaAdelaAdelaAdelaAdela wage = 1.86666 print(f'{wage:.2f}') #1.87
Part 11 基本运算符
一、算术运算符
print(2+3) print(3-2) print(2*3) print(4/2) print(4%3) print(4//3) print(2**3) #5 #1 #6 #2.0 #1 #1 #8
二、比较运算符
#第一种 pwd = '123' print(pwd == '123') print(pwd != '123') #True #False #第二种 Me_list = [1,2,'Z'] You_list = [8] She_list = [1,'a'] He_list = [1,3,4] print(Me_list < You_list) print(Me_list < He_list) print(Me_list < She_list) #True #True #报错,列表比较大小仅限于同一位置的对应的值是相同的类型,Me_list和He_list可以比较,对应最后一位转化为Ascii码,而Me_list和She_list少一位,不能比较
三、赋值运算符
age = 19 age = age + 1 print(age) #20 age = 19 age +=1 print(age) #20 age = 19 age *=10 print(age) #190
四、逻辑运算符
print(3 > 4 and 1 < 2 or 2*2 > 3) #True
注意:bool主要进行逻辑判断运算,“and” =“且”(两个都True才对)、“or”=“或”(有一个True就行)
五、身份运算符
x = 2**200 y = x z = 2**200 print(x is y) print(x is z) print(x == y) print(x == z) #True #False #True #True
注意:变量值相等id不一定相等,id相等变量值一定相等
六、Python运算符优先级
#python中True为1,False为0 print(True > 0) print(False < 1) #True #True
Part 12 流程控制之if判断
if语句主要用作判断
一、语法
if
if 条件 代码1 代码2 代码3 ... #代码块(同一缩进级别的代码,例如代码1、代码2和代码3是相同缩进的代码,这三个代码组合在一起就是一个代码块,相同缩进的代码会自上而下的运行)
light = 'green' if light == 'green': print('Go!') #Go!
if...else
if 条件: 代码1 代码2 代码3 ... else: 代码1 代码2 代码3 ...
light = 'yellow' if light == 'green': print('Go!') elif light == 'red': print('Stop!') else: print('Attention!') #Attention!
if...elif...else
if 条件1: 代码1 代码2 代码3 ... elif 条件2: 代码1 代码2 代码3 ... elif 条件3: 代码1 代码2 代码3 ... ... else: 代码1 代码2 代码3 ...
light = 'yellow' if light == 'green': print('Go!') elif light == 'red': print('Stop!') else: print('Attention!') #Attention!
二、if的嵌套
light = 'green' instruction = 'Slow Down!' if light == 'green': print('前进!') if instruction == 'Go!': print('前方道路通畅!') else: print('注意安全!') else: print('站住!') #前进! #注意安全!