如果变量是特定字符串,有没有办法让多行代码循环?

问题描述 投票:0回答:1

我正在制作一个随机数字游戏(是的,我知道是非原创的),如果你说“是”,如果你想再玩一次,我想让游戏循环 这是代码

answer = randint(1,10)
game = '''answer = randint(1,10)
input1 = input('choose a number between 1 and 10.')
if input1 == answer:
    print('you got it, good job.')
    input2 = input('do you want to play again?')
    if input2 == 'yes':
        game
    elif input2 != 'yes':
        print("ok, stopping")
elif input1 == input1 != answer:
    print ("wrong answer, the answer was")
    print(answer)
    input('do you want to play again?')
    input2 = input('do you want to play again?')
    if input2 == 'yes':
        game
    elif input2 != 'yes':
        print("ok, stopping")'''

input1 = input('choose a number between 1 and 10.')
if input1 == answer:
    print('you got it, good job.')
    input2 = input('do you want to play again?')
    if input2 == 'yes':
        game
    elif input2 != 'yes':
        print("ok, stopping")
elif input1 == input1 != answer:
    print ("wrong answer, the answer was")
    print(answer)
    input('do you want to play again?')
    input2 = input('do you want to play again?')
    if input2 == 'yes':
        game
    elif input2 != 'yes':
        print("ok, stopping")

实际的游戏也运行得很好,只是循环

如果我说“是”,事情就结束了 另外,“你想再玩一次吗”输入由于某种原因循环两次 使用 python 3.12.3 IDLE

python loops
1个回答
0
投票

要继续执行某些操作直到用户想要停止,请将整个代码包装在

while True:
循环中,如果用户回答“否”,则退出循环。否则循环将会继续。

while True:

    # game code goes here

    answer = input("Do you want to play again?")
    if answer == "no":
        break
© www.soinside.com 2019 - 2024. All rights reserved.