Python一些入门知识002控制流

Python中判断语句同样是if-else块格式如下:

number = 23

guess = int(input('Enter an integer :'))
if guess == number:
    print('Congratulations, you guessedit.')
    print('(but you do not win anyprizes!)')
elif guess < number:
    print('No, it is a little higher thanthat')
else:
    print('No, it is a little lower thanthat')

print('Done')

需要注意的就是另一个条件跟以前不同使用的是elif不再是else if,同样else跟elif块是可选项,还有一点Python中没有switch语句,可用if..elif..else来代替。

While循环不再用case选择条件,而是用if..else来进行条件判断,while同样可以有else子句,例如:

number = 23
running = True

while running:
    guess = int(input('Enter an integer :'))
    if guess == number:
        print('Congratulations, you guessedit.')
        running = False
    elif guess < number:
        print('No, it is a little higher thanthat.')
    else:
        print('No, it is a little lower thanthat.')
else:
    print('The while loop is over.')
print('Done')

 

输出:

Enter an integer : 50
No, it is a little lower than that.
Enter an integer : 22
No, it is a little higher than that.
Enter an integer : 23
Congratulations, you guessed it.
The while loop is over.
Done

For循环有一点不同,形势不再像C/C++,不过还是一样的,换汤不换药:

for i in range(1, 5):
    print(i)

else:
    print('The for loop is over')

输出:

1
2
3
4
The for loop is over

break语句还是中断循环,用简单的话来描述就是跳出循环

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    print('Length of the string is',len(s))
print('Done')

输出:

Enter something : Programming is fun
Length of the string is 18
Enter something : When the work isdone
Length of the string is 21
Enter something : if you wanna makeyour work also fun:
Length of the string is 37
Enter something : use Python!
Length of the string is 11
Enter something : quit
Done

continue语句是跳出当前循环,继续下一次循环,例:

while True:
    s = input('Enter something : ')
    if s == 'quit':
        break
    if len(s) < 3:
        print('Too small')
        continue
print('Input is of sufficient length')

输出:

Enter something : a
Too small
Enter something : 12
Too small
Enter something : abc
Input is of sufficient length
Enter something : quit


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值