简体   繁体   English

修复循环以继续执行程序,而不是在python中再次询问相同的问题

[英]Fixing a loop to continue with the program instead asking the same thing again in python

I have a problem with this dice game. 我有这个骰子游戏的问题。 When I try to make it skip to the next piece of code, it just goes back. 当我尝试使其跳至下一段代码时,它会返回。 Please help: 请帮忙:

import random  # Importing the module

decision = ('y')  # Setting variable 'decision' as y
roll_number = 1  # Setting variable 'rolling_number' as 1

name = input('What is your name?\n')  # Setting a variable as a condition so that the User can change the variable. It is an input.

while decision == ('y'):  # While loop for the decision
    if roll_number > 1:  # If loop for roll_number
        same_person = input('\nAre you the same person? If so please press y, if not please press n. Pressing anything else ask your name again!\n') #Asking if the User is the same person
        if same_person == ('y'):  # If it is the same person
            print('Okay!')  # Outputs 'Okay!'
            continue  # Skips to the next part of the code
        else:  # Otherwise
            name = input('\nWhat is your name?\n')#Asks name again

    number = random.randint(1,6)  # Generates random number between 1 and 6
    ready = input('\nPress any button to roll the die!\n')  # Lets the user know when it's ready
    print('Rolling...\n'*4)  # Output Rolling... 4 times 
    print(name,'! Your die shows a ',number,'!\n')  # Outputs the name and the number
    roll_number = roll_number+1  # Adds 1 to the variable 'roll_number'
    decision = input('Do you want to try again? If so please press y, if not please press n. Pressing anything else will stop the program!\n')  # Letting the User change the variable so they can use the program

else:  # Otherwise
    print('Bye!')  # Outputs 'Bye!'

Thank You! 谢谢!

continue only skips the rest of the body of the loop, it does not exit the loop. continue仅跳过循环主体的其余部分,它不会退出循环。 As such, when same_person == 'y' is true, you send Python back up to while decision == 'y' (note, the parenthesis around 'y' are entirely redundant here and can be omitted). 这样,当same_person == 'y'为true时,您将Python发送回至while decision == 'y' (注意,此处'y'的括号完全多余,可以省略)。

Use break to exit the loop. 使用break退出循环。 The else statement at the end of the loop will then not be executed, you may want to remove else: there and un-indent the print('Bye!') line. 然后,循环末尾的else语句将执行,您可能要删除else:在该处取消print('Bye!')行的缩进。

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

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