[英]Python while loop restarting code from the beginning
在用戶同意后,需要幫助在我的代碼中添加一個while循環以從頭開始。 每次我在代碼末尾添加它時,運行它時都會跳過它,而且我不確定該怎么做。 歡迎任何幫助。 謝謝!
print('Welcome to the Dice Game')
print(" ")
print('This program will simulate rolling a dice and will track the frequency each value is rolled.')
print(" ")
print('After rolling the dice, the program will output a summary table for the session.')
print(" ")
raw_input("Press Enter to continue...")
# function to roll the dice and get a value
def roll_dice():
r=random.randint(1,6)
return r
#to track the number of times rolled the dice
rolled=0
# to track the number of remaining turns
remaining=10000
# list to store the results
result=[]
# to track the number of sessions
sessions=0
while True:
#incrementing the session variable
sessions+=1
#getting the number of turns from the user
n=int(input("How many times would you like to roll the dice? "))
#checking the number of turns greater than remaining turns or not
if n > remaining:
print('You have only remaining',remaining)
continue
#rolling the dice according to the value of n
if rolled <= 10000 and n <= remaining :
for i in range(n):
result.append(roll_dice())
#updating the remaining turns and rolled variables
remaining=remaining-n
rolled=rolled+n
#printing the results and session variable
if rolled==10000:
print('---------------')
for i in range(len(result)):
print('|{:7d} | {:d} |'.format( i+1,result[i]))
print('---------------')
print('Rolled 10000 times in %d sessions' % sessions)
sys.exit(0)
您的rolled
, remaining
, result
和sessions
變量將在while循環的下一次迭代中保留。 您需要在循環的每次迭代中重新定義變量,因為您正在檢查remaining
變量以檢查用戶的轉向是否結束。
所以代替:
def roll_dice():
# ...
rolled = 0
remaining = 10000
result = []
sessions = 0
while True:
# ...
你需要:
def roll_dice():
# ...
while True:
rolled = 0
remaining = 10000
result = []
sessions = 0
# ...
我在您的代碼中看到許多不必要的變量和比較,更干凈的代碼通常可以減少錯誤並提高可讀性。
我建議是這樣的:
def do_dice_game(rounds=1000):
sessions = 0
rolls = []
while rounds > 0:
sessions += 1
user_input = rounds + 1
while user_input > rounds:
user_input = int(raw_input("..."))
rolls += [random.randint(1, 6) for i in range(user_input)]
rounds -= user_input
# print something
def do_games():
to_continue = True
while to_continue:
do_dice_game()
to_continue = raw_input("...") == "continue"
另外,根據您的代碼,每個會話的編號對最終的“滾動”結果沒有影響。 您始終可以只記錄會話數,然后在末尾滾動1000個隨機數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.