玩家回答后如何再次运行我的代码?

时间:2018-08-08 05:35:29

标签: python python-3.7

import random
def playGame(errmsg):
    done = 0
    while(done != 1):
        try:
            SInput = input("What is the lowest number?")
            LInput = input("What is the highest number?")
            s = int(SInput)
            l = int(LInput)
            if s > l:
                print(errmsg)
        except:
            print(errmsg)
        done = 1
    while(done != 2):
        try:
            answer = random.randint(s, l)
            replyInput = input("Guess the number!(%d - %d)" % (s, l))
            reply = int(replyInput)
            if reply < answer:
                print("Your guess is too small! Please guess a larger number!")
            elif reply > answer:
                print("Your guess is too large! Please guess a smaller number!")
            elif reply == answer:
                print("You guessed the correct number!")
                done = 2
        except:
            print(errmsg)
    playAgain = input("Do you want to play again?(Y/N)")
    if playAgain == "Y":
        done = 0
    elif playAgain == "N":
        print("Bye!")
playGame("Please input a valid number")

如何使代码重新启动并生成另一个数字?

2 个答案:

答案 0 :(得分:0)

您可以在函数中添加一行,以返回True或False,表示他们是否要再次播放。然后,在您调用“ playgame”函数的地方放一个while循环,当该函数返回false时,该循环会中断。

为简洁起见,通过移动设备发送

答案 1 :(得分:0)

您可以在if条件中添加playGame("Please input a valid number"),以检查用户是否回答“是”。

if playAgain == "Y":
    done = 0
    playGame("Please input a valid number")

它将递归运行,直到您输入N

我还建议您在while循环外添加answer = random.randint(s, l)代码,因为每次循环都会生成随机选择,并且由于提示可能无效,用户可能无法正确猜测它为下一次迭代。做类似的事情:

answer = random.randint(s, l)
    while(done != 2):