Pythonの基礎知識(三)--基本的な異常処理、算術演算子、入出力
例外処理
- 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)
*主なプロセスができるだけ明確であることを保証するために、例外処理モジュールをプログラムの最後に配置する必要があります.