分支、循环、条件与枚举

                                        分支、循环、条件与枚举

一、什么是表达式

    表达式(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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值