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