【问题标题】:How do you use an if statment to only except integers and give an invalid entry message?如何使用 if 语句只接受整数并给出无效的条目消息?
【发布时间】:2019-10-11 14:29:19
【问题描述】:

我正在用 python 做一个简单的猜谜游戏,并试图在用户输入任何不是整数的输入时创建一个“无效输入”消息。

我尝试在 if 语句中只使用“int”来处理所有整数,但这不起作用。 我知道我的语法错误。我只是不确定正确的语法是什么。

import random
play = True

while play:
    count = 1

    hidden = random.randrange(1,5)


    guess = int(input("Guess a number between 1 and 5:"))

    if guess != int
        guess = int(input("Invalid Entry. Please enter an Integer between 1 and 5:"))


    while guess != hidden:
        count+=1
        if guess > hidden + 10:
            print("your guess is to high!")
        elif guess < hidden -10:
            print("your too low!")
        elif guess > hidden:
            print("your really warm, but still to high!")
        elif guess < hidden:
            print("your really warm, but still to low")

        print("You have guessed incorrectly, Try again!. \n")
        #reset the guess variable and make another guess
        guess = int(input("Guess a number between 1 and 5:"))

    print("Nice!!! Your guess was correct!\n you got the correct number in" , count , "tries.")

    count = 1


    playagain = str(input("Do you want to play again?\nType yes or no: "))
    if playagain == "no" or "n" or "N" or "no thank you":
        play = False

    elif playagain == "yes" or "y" or "Y" or "YES" or "yes":
        play = True

    else: playagain != "yes" or "y" or "Y" or "YES" or "yes" "no" or "n" or "N" or "no thank you"
    playagain = str(input("Invalid Entry. Please Type yes or no: "))

这是我遇到的错误。我的代码中可能还有其他一些错误。

File "comrandomguess.py", line 18
    if guess != int
                  ^
SyntaxError: invalid syntax

【问题讨论】:

  • if 条件后忘记加冒号:,因此出现语法错误
  • 好的,我在if 语句之后修复了缺失的:。现在我收到一条消息``` Invalid Entry。请输入一个介于 1 和 5 之间的整数:``` 即使在输入任何数字之后也是如此。
  • 在给定in this answer 的情况下,您最好使用例程sanitised_input。特别是,请致电sanitised_input('Guess a number between 1 and 5:', type_=int, min_=1, max_=5)。或者sanitised_input('Guess a number between 1 and 5:', range_=[1,2,3,4,5]).

标签: python python-3.x


【解决方案1】:

我总是用这种方法来检查某个东西是否不是整数:

Python 3

if not round(guess) == guess: print("Do Stuff")

Python 2

if not round(guess) == guess: print "Do Stuff"

【讨论】:

  • 这不是我想要的。我只需要一个条件语句来捕获不是整数的所有内容并输出消息“无效条目”,然后它们会返回提示再次尝试。
【解决方案2】:

你需要做这样的事情:

play = True

while play:
    guess = input("Guess a number between 1 and 5: ")

    try:
        number = int(guess)
    except ValueError:
        print("You need to input an integer.")
        continue

    if number < 1 or number > 5:
        print("You need to input an integer between 1 and 5.")
        continue

    # ...

    print("Your number was: " + guess)
    play = False

当你第一次使用input() 时,你会得到一个字符串。如果你尝试通过 int(input()) 立即将该字符串转换为整数,并且如果玩家键入了类似“abcd”的字符串,那么 Python 将引发异常。

>>> int(input("Guess a number: "))
Guess a number: abcd
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abcd'

为避免这种情况,您必须通过在 try/except block 中执行 int(guess) 来处理异常。

continue statement 会跳回到 while 循环的开头,因此如果您使用它,您只需要求输入一次即可。

【讨论】:

  • 我现在能够让它适用于低于 1 和高于 5 的值但是当我输入字符串时它仍然会吐出错误消息。当输入字符串(如字母或单词)时,有没有办法打印出“无效条目”消息?
  • 您是否复制并粘贴了我的示例代码而没有做任何改动?如果你输入一个字符串,它应该打印“你需要输入一个整数”。
【解决方案3】:

将用户输入解析为字符串以避免ValueError

guess = input("Guess a number between 1 and 5: ")

while not guess.isdigit() or int(guess) > 5 or int(guess) < 1: 
    guess = input("Invalid Entry. Please enter an Integer between 1 and 5: ")

guess = int(guess)

以上代码确保用户输入是一个正整数,并且介于 1 和 5 之间。接下来,将用户输入转换为整数以供进一步使用。

此外,如果您想检查 python 对象/变量的数据类型,请使用isinstance 方法。示例:

a = 2
isinstance(a, int)

Output:
>>> True

【讨论】:

  • 这会破坏被分类为数字但无法在 Python 中转换为 int 的 Unicode 字符。例如,"①".isdigit() 为 True,但 int("①") 引发 ValueError。
  • @JackTaylor,谢谢!我没有意识到这一点。但是,一般用户不会像这样输入 Unicode 字符,除非他们坚决破坏程序。
【解决方案4】:

如果您真的想验证用户输入是否为 int,您希望将输入保持为字符串形式。然后编写一个小函数来测试输入。在这里,我将使用列表推导和字符串连接和 isdigit 方法,以确保用户仅在字符串中输入了数字 0-9,即此函数返回 True(否则为 False)(*根据 Jack Taylor 评论修改下面,同样适用于 s = '' 情况):

def testForInt(s):
    if s:
        try:
            _ = s.encode('ascii')
        except UnicodeEncodeError:
            return False
        test = ''.join([x for x in s if x.isdigit()])
        return (test == s)
    else:
        return False

如果您想将用户完全沙箱化,请将其包装在这样的循环中:

acceptable = False
while not acceptable:
    entry = input("Enter an int: ")
    if testForInt(entry):
        entry = int(entry)
        acceptable = True
    else:
        print("Invalid Entry")

如果您想要一个没有函数调用的更简单版本(请参阅 Jack Taylor 评论),这也可以:

acceptable = False
while not acceptable:
    entry = input("Enter an int: ")
    try:
        entry = int(entry)
        acceptable = True
    except ValueError as e:
        print(f"Failed due to {str(e)}")

现在您已经有了您所知道的 int,不用担心。如果始终如一地实施,这种验证用户输入的方法可以省去很多麻烦。参见 SQL 注入等。

【讨论】:

  • 这种方法存在与@Deepankar 相同的缺点。如果你输入一个像“①”这样的字符串,那么它会通过 testForInt 函数,但是当你真正尝试将它转换为 int 时,程序会引发异常。
  • @JackTaylor 谢谢,我在 try/except 块中尝试了字符串 encode('ascii') 方法,它似乎可以工作......
  • 为什么不在 try/except 块中使用 int(entry)?这对我来说似乎要简单得多。
  • 完美这就是我所需要的谢谢@neureino_logic
  • 是的,这更简单......从 C++ 到 Python,我认为比起“pythonic”标准,我更不愿意使用异常。感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多