简体   繁体   English

为什么在用户要求重新启动程序后不重置代码?

[英]Why it doesn't reset the code after the user asks to restart the program?

So this is my code.所以这是我的代码。 Upgraded.升级了。 I had some issues with the While loops but I ve managed to get over it.我在 While 循环方面遇到了一些问题,但我设法克服了它。 Now my problem is this.现在我的问题是这个。 When the user gets at the end of the loop and is being asked to play again the program won t change its random number.当用户到达循环结束并被要求再次播放时,程序不会更改其随机数。 Any help would be really appreciated.任何帮助将非常感激。 And as the title says, python won t recognize capital Y and N and it will only take y and n.正如标题所说,python 不会识别大写的 Y 和 N,它只会接受 y 和 n。

from random import *
def play():
    return guess()

def retry():
    while True:
        replay = input("Try again ?(Y/N)")
        if replay not in {"y", "n"}:
            print("Please enter Yes or No")
        elif replay.lower() == "n":
            print("Thanks for playing! Bye now!.")
            break
        elif replay.lower() == "y":
            print("As you wish!")
            return guess()

def guess():
    while True:
        user = int(input("Guess the number: \n"))
        print(user,a)
        if user < a:
            print("Higher")
        elif user > a:
            print("Lower")
        if user == a:
            return retry()
a = randint(0,20)



play()

It doesn't reset a because it was never instructed to do so.它不会重置a因为它从未被指示这样做。 When you restart the game, you should generate a new number:当您重新启动游戏时,您应该生成一个新数字:

...
        elif replay.lower() == "y":
            print("As you wish!")

            # Tell the interpreter that we want to modify a variable from the global scope
            global a

            # Generate a new random number
            a = randint(0,20)

            return guess()

...

And as the title says, python won t recognize capital Y and N and it will only take y and n正如标题所说,python 不会识别大写的 Y 和 N,它只需要 y 和 n

You should change the following line:您应该更改以下行:

        replay = input("Try again ?(Y/N)")

To:到:

        replay = input("Try again ?(Y/N)").lower()

Otherwise your following condition will fail, because Y and N are not in {"y", "n"} .否则您的以下条件将失败,因为YN不在{"y", "n"} Though, the brackets doesn't really make sense here, and would be better to simply do:虽然,括号在这里没有意义,最好简单地做:

if replay not in "yn":

EDIT: Instead of validating the answer twice, just look for valid answers and then ask for a valid one if it wasn't provided:编辑:不要验证答案两次,只需寻找有效答案,如果未提供,则要求提供有效答案:

replay = input("Try again ?(Y/N)").lower()
if replay == 'y':
    # replay...
elif replay = 'n'
    print("Thanks for playing! Bye now!.")
    break
else:
    print("Please enter Yes or No")

EDIT: To ensure the given input is a valid number, you could use a try/except block to catch the error:编辑:为确保给定的输入是有效数字,您可以使用try/except块来捕获错误:

try:
    user = int(input("Guess the number: \n"))
except ValueError:
    print('Not a valid number.')

Or you could ensure the given string is a number using str.isdigit :或者您可以使用str.isdigit确保给定的字符串是一个数字:

user = input("Guess the number: \n")
if user.isdigit():
    user = int(user)
else:
    print('Not a valid number.')

I would personally go with the try/except since the second is basically validating the string twice (once through isdigit , then another when the int cast is done).我个人会使用try/except因为第二个基本上验证字符串两次(一次通过isdigit ,然后在int完成后再次验证)。

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

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