Python while循环从头开始重新启动代码
需要帮助在我的代码中添加while循环,以便在用户同意后重新开始。每次我在代码末尾添加它时,当我运行它时,它都会跳过它,我根本不知道该怎么做。欢迎任何帮助。谢谢大家!Python while循环从头开始重新启动代码,python,loops,while-loop,Python,Loops,While Loop,需要帮助在我的代码中添加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('A
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)
print('欢迎参加骰子游戏')
打印(“”)
print('此程序将模拟掷骰子,并跟踪每个值的掷骰频率')
打印(“”)
print('掷骰子后,程序将输出会话的摘要表')
打印(“”)
原始输入(“按回车键继续…”)
#函数来掷骰子并获得一个值
def掷骰子():
r=random.randint(1,6)
返回r
#跟踪掷骰子的次数
滚动=0
#跟踪剩余圈数的步骤
剩余=10000
#列表以存储结果
结果=[]
#跟踪会话数的步骤
会话=0
尽管如此:
#递增会话变量
会话数+=1
#从用户处获取圈数
n=int(输入(“您想掷骰子多少次?”)
#检查圈数是否大于剩余圈数
如果n>剩余:
打印(“您只有剩余的”,剩余的)
持续
#根据n的值滚动骰子
如果滚动您的滚动
,剩余
,结果
和会话
变量在while循环的下一次迭代中保持不变。您需要在循环的每次迭代中重新定义变量,因为您要对照剩余的变量来检查用户的任务是否结束
因此,不是:
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个随机数 这使我的代码更简洁,但仍然不确定在哪里添加第二部分,以使游戏重新启动或退出。谢谢,但如何循环,使其重新启动或退出?