简体   繁体   English

Python同时循环从头开始重新启动代码

[英]Python while loop restarting code from the beginning

Need help adding a while loop to my code to start it from the beginning again after the user agrees to it. 在用户同意后,需要帮助在我的代码中添加一个while循环以从头开始。 Every time I add it at the end of the code it skips it when I run it and I'm not sure how to do it at all. 每次我在代码末尾添加它时,运行它时都会跳过它,而且我不确定该怎么做。 Any help is welcomed. 欢迎任何帮助。 Thank you! 谢谢!

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)

Your rolled , remaining , result and sessions variables persist on the next iteration of the while loop. 您的rolledremainingresultsessions变量将在while循环的下一次迭代中保留。 You need to redefine the variables on each iteration of the loop, because you're checking against the remaining variable to check if the user's turn is over. 您需要在循环的每次迭代中重新定义变量,因为您正在检查remaining变量以检查用户的转向是否结束。
So instead of: 所以代替:

def roll_dice():
    # ...

rolled = 0
remaining = 10000
result = []
sessions = 0

while True:
    # ...

you need: 你需要:

def roll_dice():
    # ...

while True:
    rolled = 0
    remaining = 10000
    result = []
    sessions = 0
    # ...

I see many unnecessary variables and comparisons in your code, a cleaner code usually results less bugs and better readability. 我在您的代码中看到许多不必要的变量和比较,更干净的代码通常可以减少错误并提高可读性。

I suggest something like this: 我建议是这样的:

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"

Also, according to your code, numbers of each session has no effect on the final "rolled" result. 另外,根据您的代码,每个会话的编号对最终的“滚动”结果没有影响。 You can always just record the number of sessions and then roll 1000 random numbers at the end. 您始终可以只记录会话数,然后在末尾滚动1000个随机数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM