简体   繁体   中英

Is there any way in python to repeat a while or for loop by asking the user to do so at the end of the loop?

I'm just starting to learn Python and I'm writing a simple dice rolling program that asks the user for the number of dice and how many sides the dice will have.

So far I have this:

numberOfDice = eval(input("How many dice/die would you like to use? "))
numberOfSides = eval(input("How many sides will each die have? "))

for i in range(1,numberOfDice + 1) :
    roll = random.randint(1,numberOfSides)
    print(roll)

while True :
    replay = input("Would you like to play again?     ")
    if replay.lower() == "yes" :
        numberOfDice = eval(input("How many dice/die would you like to use?     "))
        numberOfSides = eval(input("How many sides will each die have?     "))
        for i in range(1,numberOfDice + 1) :
            roll = random.randint(1,numberOfSides)
            print(roll)
    else :
        break

It works, but it doesn't seem very efficient to me. I'm wondering if there might be a way to ask the user at the end of the first for loop if they want to play again, and, if they say yes, ask them for new values and repeat the for loop again. Is there any way to do something like this?

The general application is a "stay while valid" loop, such as:

replay = True
while replay:
    ... remainder of code
    replay = raw_input("Roll again? (y or n)") == 'y'

Note that this is a simple version, with no error checking: if the user enters a 'y', the program continues; anything else terminates the wonderful world of rolling a douse (never say 'die' :-) ).

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