表达式(Expression)是运算符(operator)和操作数(operand)所构成的序列。
例如:
1、1 + 1
2、a = [1, 2, 3]
3、a > b
4、a = 1 + 2 * 3
5、a = 1, b = 2
c = a and b and c
6、c = int("1") + 2
从最高到最低优先级的所有运算符:
运算符描述**指数 (最高优先级)~ + -按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)* / % //乘,除,取模和取整除+ -加法减法>> <<右移,左移运算符&位 'AND'^ |位运算符<= < > >=比较运算符<> == !=等于运算符= %= /= //= -= += *= **=赋值运算符is is not身份运算符in not in成员运算符not and or逻辑运算符1、snippet
2、嵌套分支:
condition = True if condition: if condition: pass else: pass else: if condition: pass else: pass3、代码块概念:
condition = True if condition: code1 code11 code2 code22 code3 code33 else: code1 code11 code2 code22 code3 code331、原始写法:
a = input() print("a is " + a) print(type(a)) if a == "1": print("apple") else: if a == "2": print("orange") else: if a == "3": print("banana") else: print("shopping") 运行结果: 2 a is 2 <class 'str'> orange2、优化写法:
a = input() print("a is " + a) print(type(a)) if a == "1": print("apple") elif a == "2": print("orange") elif a == "3": print("banana") else: print("shopping") 运行结果: 2 a is 2 <class 'str'> orange示例:
# 1、a和b不可能同时为False # 2、打印为True的值 # 方式一: a = 1 b = 0 if a == True: print("True is a") else: print("True is b") 运行结果: True is a # 方式二: print(a or b) 运行结果: 1
