# 修改 end 变量 fruits = ['apple', 'banana'] print("This is printed with default end") for item in fruits: print(item) # This is printed with default end # apple # fruit
print("This is printed with 'end='&''") for item in fruits: print(item, end='&') # This is printed with 'end='&'' apple&banana&
number = 5 if number < 3: print('Number is smaller than 3.') elif number < 7: print('Number is between 3 and 7.') else: print('Number is greater than 7.') # Number is between 3 and 7.
count = 0 while count <5: print(f'{count} is less than 5') count += 1 else: print(f'{count} is not less than 5') # count is less than 5 # count is less than 5 # count is less than 5 # count is less than 5 # count is less than 5 # count is not less than 5 count = 0 while count < 5: print(f'{count} is less than 5') count = 6 break else: print(f'count is not less than 5') # 0 is less than 5
for 循环
1 2
for 迭代变量 in 迭代器: action
for 循环是迭代循环,在 Python 中相当于一个通用的序列迭代器,可以遍历任何有序序列,如 str、list、tuple 等,也可以遍历任何可迭代对象,如 dict。
1 2 3 4 5
for s in'abc': print(s) # a # b # c
for-else 循环
当 for 循环正常执行完的情况下,执行 else 输出,如果 for 循环中执行了跳出循环的语句,比如 break,将不执行 else 代码块的内容,与 while - else 语句一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for i in range(2): print(i) else: print('done') # 0 # 1 # done for i in range(2): if i % 2 == 1: break print(i) else: print('done') # 0
range 函数
1
range([start,] stop[, step=1])
range 这个内置函数的作用是生成一个从 start 参数的值开始到 stop参数的值结束的数字序列,该序列包含 start 的值但不包含 stop 的值。
1 2 3 4
for i in range(1, 5, 2): print(i) # 1 # 3
enumerate 函数
1
enumerate(sequence, [start=0])
返回枚举对象,可与 for 循环连用。
1 2 3 4 5 6 7 8 9 10
letters = ['a', 'b', 'c', 'd'] lst = list(enumerate(letters)) print(lst) # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] for idx, letter in enumerate(letters, 1): print(idx, letter) # 1 a # 2 b # 3 c # 4 d
break 语句
break 语句可以跳出当前所在层的循环,例子见上。
continue 语句
continue 终止本轮循环并开始下一轮循环。
1 2 3 4 5
for i in range(3): ifnot i % 2: continue print(i) # 1
defdivide(x, y): try: result = x / y print("result is", result) except ZeroDivisionError: print("division by zero!") finally: print("executing finally clause")
divide(2, 1) # result is 2.0 # executing finally clause divide(2, 0) # division by zero! # executing finally clause divide("2", "1") # executing finally clause --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-79-16805cf48925> in <module> 15# division by zero! 16# executing finally clause ---> 17 divide("2", "1") 18# executing finally clause 19# TypeError: unsupported operand type(s) for /: 'str' and 'str'
<ipython-input-79-16805cf48925> in divide(x, y) 1defdivide(x, y): 2try: ----> 3 result = x / y 4 print("result is", result) 5except ZeroDivisionError:
TypeError: unsupported operand type(s) for /: 'str'and'str'