>>> x = int(input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print('Negative changed to zero') ... elif x == 0: ... print('Zero') ... elif x == 1: ... print('Single') ... else: ... print('More') ... More
for语句
对任意序列进行迭代(例如列表或字符串),条目的迭代顺序与它们在序列中出现的顺序一致。
1 2 3 4 5 6 7 8
>>> # Measure some strings: ... words = ['cat', 'window', 'defenestrate'] >>> for w in words: ... print(w, len(w)) ... cat 3 window 6 defenestrate 12
>>> for n inrange(2, 10): ... for x inrange(2, n): ... if n % x == 0: ... print(n, 'equals', x, '*', n//x) ... break ... else: ... # loop fell through without finding a factor ... print(n, 'is a prime number') ... 2is a prime number 3is a prime number 4 equals 2 * 2 5is a prime number 6 equals 2 * 3 7is a prime number 8 equals 2 * 4 9 equals 3 * 3
break语句
break 语句,和 C 中的类似,用于跳出最近的 for 或 while 循环.
continue语句
continue 语句也是借鉴自 C 语言,表示继续循环中的下一次迭代:
1 2 3 4 5 6 7 8 9 10 11 12 13
>>> for num in range(2, 10): ... if num % 2 == 0: ... print("Found an even number", num) ... continue ... print("Found an odd number", num) Found an even number 2 Found an odd number 3 Found an even number 4 Found an odd number 5 Found an even number 6 Found an odd number 7 Found an even number 8 Found an odd number 9