countをprint文で出力できません。
# -*- coding: utf-8 -*- global count count =0 def hanoi(n, x, y, z): if n == 1: print("{}→{}".format(x, y)) count +=1 else: hanoi(n-1, x, z, y) print("{}→{}".format(x, y)) count += 1 hanoi(n-1, z, y, x) print(hanoi(3, "A", "C", "B")) print(count)
とコードを書きました。print文が何回呼ばれたかをカウントしたいのですが、このコードを実行すると
UnboundLocalError: local variable 'count' referenced before assignment
とエラーが出ました。
このエラーを検索して、どうやらdefの中にglobal countを書けばエラーが消えるらしいと知ったので、
# -*- coding: utf-8 -*- def hanoi(n, x, y, z): global count count = 0 if n == 1: print("{}→{}".format(x, y)) count +=1 else: hanoi(n-1, x, z, y) print("{}→{}".format(x, y)) count += 1 hanoi(n-1, z, y, x) print(hanoi(3, "A", "C", "B")) print(count)
とコードを書き直したらprint文が通りました。
しかし、どうして一番最初の書き方が間違いなのかわかりません。
globalとつけたらスコープが関係なくどこからでもアクセスできると習ったので...。
どうして一番最初の書き方が間違いなのでしょうか?
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/11 00:21
2017/07/11 00:26