異常處理
- 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)
* 應該盡量將異常處理模組放在程式末尾,以保證主要流程儘可能清晰