猜游戏isdigit帮助python

时间:2018-07-01 07:12:11

标签: python

我创建了一个猜谜游戏,只允许用户键入4个数字。我的错误是“'int'对象没有属性'isdigit'”。我正在尝试这样做,以便当用户键入字母时显示错误消息,例如“仅键入数字”,并让用户再次猜测。有人可以给我建议吗?

谢谢!

对不起,我的英语(不是我的母语)

import random
n = random.randint(0, 9999)
guesses = 0
print()

while True: 

  guess = (input("Enter number from 0 to 9999"))
  guess = int(guess)

  if not guess.isdigit():
      print("Only numbers are allowed")

  else:
    guess = int(guess)
    guesses = guesses + 1

    if len(str(guess)) != 4:
      print (guesses, guess, "Invalid! 4 characters only")
      print()

    elif guess < n:
      print (guesses, guess, "too low")
      print()

    elif guess > n:
      print (guesses, guess, "too high")
      print()

    elif guess == n:
      break

print (guesses ,guess, "You guessed it!")

2 个答案:

答案 0 :(得分:1)

isdigit仅可用于字符串,不能用于int

您必须检查是否可以通过调用int将给定的字符串转换为isdigit,然后再转换为int

if not guess.isdigit():
    print("Only numbers are allowed")

guess = int(guess)

答案 1 :(得分:0)

Python鼓励使用EAFP,因此您可以编写以下代码:

guess = input("Enter number from 0 to 9999")

try:
    guess = int(guess)
except ValueError:
    print("Only numbers are allowed")
    continue

当从输入字符串到整数的转换失败时,内置转换器将引发ValueError。而且,当您遇到这样的错误时,您就知道它不是有效的整数,可以采取相应的措施。