私はwhileループを実行して、サイコロの数とランダムなサイコロをする側の数を入力するようにPythonに問題があります。 2番目のループと追加のループで、私は彼らが続行したいかどうか質問したい。 'n'または 'no'を入力すると、プログラムは終了します。フローを制御するローカルブールを設定する
私はグローバル変数を使ってこのロジックを動作させることができました。初めて変数を呼び出すと関数内でその変数を変更することができました。このようなグローバル変数は、非常にPythonのやり方ではありません。私はこれを改善したいと思います。
次のコードは、ユーザーに終了を求めることがないという点を除いて機能します。これは変数がwhileループの始めにTrueに設定され続けるためですが、グローバル変数に頼らずにフラグを設定する方法はわかりません。
True/False変数をローカル(非グローバル)に設定し、それをプログラムのフローを制御するために使用するにはどうすればよいですか?
import sys
import random
def get_user_input(first_loop):
if not first_loop:
another_time = input("Would you like to roll another time?")
if another_time.lower() in ['n', 'no']:
sys.exit()
# This allows the code above to output on additional loops.
first_loop = False
return first_loop
while True:
# How do I not reset this back to True each time the program loops?
first_loop = True
get_user_input(first_loop)
number_of_dice = int(input("Enter the number of dice you would like to roll: "))
number_of_sides = int(input("Enter the number of sides for the dice: "))
# create the dice_total list so each time we create a roll in the loop,
# it can be added to a list and the total calculated
dice_total = []
for die in range(number_of_dice):
random_roll = random.randrange(1, number_of_sides)
print("You rolled: ", random_roll)
dice_total.append(random_roll)
dice_total = sum(dice_total)
print("The total of the dice rolled is: ", dice_total)
これはこれをグローバル変数にしませんか、グローバル変数を正しく理解できませんか? – Phorden
このコードはグローバル変数を使用しません。 'first_loop'変数をループ外に移動して一度初期化します。一般的に言えば、 'global'キーワードはコードのモジュール化が少なくメンテナンス性が低いコード臭です。 –
@ReutSharabaniグローバル変数は、関数/メソッドに対してローカルではない、つまりファイルスコープに存在する変数です。初期化変数をループから抜き出しても、それをグローバルにすることはできません。周囲の機能に対してはまだローカルです。 – antred