python入门

分支

if-else

python中不需要用花括号来指定流程控制语句的作用范围,而是直接靠语句的位置来体现

mood = True
if mood:
    print('go to left')
    print('go away')
mood = False
if mood:
    print('go to left')
print('go away')

在这里插入图片描述

进一步应用:

account = 'account'
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')

在这里插入图片描述

if - elif - else

a = input()
a = int(a)
if a == 1:
    print('apple')
elif a == 2:
    print('orange')
elif a == 3:
    print('banana')
else:
    print('shopping')

在这里插入图片描述

注:此处直接输入数字会被直接识别为字符串str形式,所以必须强制转化为int类型才能继续比较

循环

while 循环

  • while可以与else 搭配使用
counter = 0
while counter <= 10:
    counter += 1
    print(counter)
else:
    print('EOR')

    

在这里插入图片描述

for循环

  • for循环主要用来遍历序列,集合,元组,字典中的元素
a = ['apple', 'orange', 'banana']
for x in a:
    print(x)

在这里插入图片描述
打印子列表

a = [['apple', 'orange', 'banana'], (1, 2, 3)]
for x in a:
    for y in x:
        print(y)

在这里插入图片描述

for - else和break联用

break会直接跳出当前循环

a = [1, 2, 3]
for x in a:
    if x == 2:
        break
    print(x)
else:
    print('EOR')

在这里插入图片描述
特殊情况:

a = [['apple', 'orange', 'banana'], (1, 2, 3)]
for x in a:
    for y in x:
        if y == 'orange':
            break
        print(y)

else:
    print('fruit is gone')

在这里插入图片描述

上述两种都是for- else循环为什么一个碰到break会退出而另一个不会?
因为第一个是单层for循环,而第二个是双层for循环。
只有当跳出所有的for循环后,else内的内容才会被跳过

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值