异常处理
- try:
- try_suite
- except exception1 as variable1:
- exception_suite1
- ...
- except exceptionN as variableN:
- exception_suiteN
- s = input("enter an integer:")
- try:
- i = int(s)
- print("valid integer entered:", i)
- except ValueError as err:
- print(err)
- #invalid literal for int() with base 10: '3.5'
算术运算符
+ - * / += ...
- seeds = ['sesame', 'sunflower', 'pumpkin']
- seeds += ['poppy']
- print(seeds)
- #['sesame', 'sunflower', 'pumpkin', 'poppy']
- #这个时候的运算同seeds.append('poppy')等价
- seeds += 2
- #TypeError: 'int' object is not iterable
- #类型不匹配
- seeds += 'durian'
- print(seeds)
- #['sesame', 'sunflower', 'pumpkin', 'poppy', 'd', 'u', 'r', 'i', 'a', 'n']
- #不同类型的即便可以执行,也会出现比较奇怪的结果
- #这个时候用seeds.append('durian')可得到正确的结果
输入/输出
input()
print()
- #!user/bin/env python3
- print("Type integers, each followed by Enter; or just Enter to finish")
- total = 0
- count = 0
- while True:
- line = input("integer:") #输入数字
- if line: #如果非空
- try:
- number = int(line) #转换成整数
- except ValueError as err:
- print(err) #非整数
- continue
- total += number
- count += 1
- else:
- break
- if count:
- print("count = ", count, "total = ", total, "mean = ", total / count)
* 应该尽量将异常处理模块放在程序末尾,以保证主要流程尽可能清晰