简体   繁体   中英

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. 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. 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.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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