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

时间:2013-11-28 18:55:32

标签: python python-3.x

这个骰子游戏有问题。当我试图让它跳到下一段代码时,它就会回来。请帮忙:

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!'

谢谢!

1 个答案:

答案 0 :(得分:0)

continue仅跳过循环体的其余部分,它不会退出循环。因此,当same_person == 'y'为真时,您将Python发送回while decision == 'y'(注意,'y'周围的括号在这里完全是多余的,可以省略。)

使用break退出循环。然后,循环结束时的else语句将执行,您可能希望删除else:并取消缩进print('Bye!')行。< / p>