deffib(n):if n ==0or n ==1:return n
else:return fib(n -1)+ fib(n -2)
defhanoi(a,b,c,n):if n ==1:print(a,'->',c)else:
hanoi(a,c,b,n-1)#借由c先移动到b上print(a,'->',c)
hanoi(b,a,c,n-1)#出口是n=1时
deffoo(num,base):if num >= base:
foo(num // base, base)print(num % base, end =' ')
foo(126,2)1111110
変数のスコープ
グローバル変数
プログラム・コードの本体部分は、グローバル変数であります
グローバルと同じ名前のローカル変数は、インナーシールド層の原則に従ってください
グローバル変数に値を変更することはできません機能で
a =3deff():
a =5print(a **2)25
global文は、グローバル変数を強調しました
deff(x):global a
print(a)
a =5print(a + x)
a =3
f(8)print(a)3135
ローカル変数
変数は、関数内のローカル変数です
異常な
BaseException:すべての例外の基底クラス
例外:一般的な例外の基底クラス
AttributeError:オブジェクトのプロパティが存在しません
IndexError:いいえ、そのようなシーケンスインデックス
I0Error:入力/出力操作に失敗しました
KeyboardInterrupt:ユーザ割込みは実行します
KeyError例外:このキーは、マップは存在しません。
NameError:名前(変数)を見つけることができません
SyntaxError:Pythonの構文エラー
TypeError例外:操作の無効なタイプ
ValueError:無効なパラメータが渡されました
ZeroDivisionError:計算に加えて、第2のパラメータは、0であります
例外処理
試す-以外キャッチ例外へ
試す-以外の文法
try:raiseexcept Exceetion as err:print(err)
try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)#检测语句块except ValueError:#异常类名print('Please input a digit!')#异常处理
句ブロック以外異常複数の捕捉複数除きます
try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)except ValueError:print('Please input a digit!')except ZeroDivisionError:print('The second number cannot be zero!')
try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)except(ValueError,ZeroDivisionError):print('Please input a digit!')
すべての例外をキャッチ
try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)except Exception as err:print('Something went wrong!')print(err)
else節を追加することができます
try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)except Exception as err:print('Something went wrong!')print(err)else:print('everything is OK!')
循環プロセス
whileTrue:try:
num1 =int(input('enter the first number:'))
num2 =int(input('enter the second number:'))print(num1 / num2)breakexcept Exception as err:print('Something went wrong!')print(err)else:print('everything is OK!')
finally節にかかわらず、例外がfinally節が実行されるべき発生するかどうかの
コンテキストマネージャ(コンテキストマネージャー)とのステートメントで
try:
f =open('data.txt')for line in f:print(line,end='')except IOError:print('cannot open the file!')finally:
f.close()#文件是否正常打开都对它进行关闭,当文件不能打开时会出错
withopen('data.txt')as f:#把上下文管理表达式的值赋给变量for line in f:print(line,end='')