分支、循环、条件与枚举

it2022-05-05  67

                                        分支、循环、条件与枚举

一、什么是表达式

    表达式(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逻辑运算符

三、表达式优先级练习

>>> a = 1 >>> b = 2 >>> c = 3 >>> not a or b + 2 == c False >>> (not a) or ((b + 2) == c) False >>> not (a or b) + 2 == c False

四、流程控制语句之条件控制

ACCOUNT = "qiyue" # 常量 PASSWORD = "123456" # 常量 print("please input account") user_account = input() print("please input password") user_password = input() if ACCOUNT == user_account and PASSWORD == user_password: print("success") else: print("fail") 运行结果: please input account qiyue please input password 123456 success

五、常量与Pylint的规范    

ACCOUNT = "qiyue" # 常量 PASSWORD = "123456" # 常量 print("please input account") user_account = input() print("please input password") user_password = input() if ACCOUNT == user_account and PASSWORD == user_password: print("success") else: print("fail") 运行结果: please input account qiyue please input password 123456 success

六、流程控制语句之条件控制:snippet、嵌套分支、代码块概念

    1、snippet

    2、嵌套分支:

condition = True if condition: if condition: pass else: pass else: if condition: pass else: pass

    3、代码块概念:

condition = True if condition: code1 code11 code2 code22 code3 code33 else: code1 code11 code2 code22 code3 code33

七、流程控制语句之条件控制:elif的优点

    1、原始写法:

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'> orange

    2、优化写法:

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

 


最新回复(0)