在“ builtin_function_or_method”和“ int”的实例之间不支持TypeError:“>”

时间:2018-12-03 07:46:23

标签: python python-3.x

我正在开发游戏,但是我的代码有问题。这是错误,非常感谢任何帮助!

Traceback (most recent call last):
  File "main.py", line 18, in <module>
    elif choice > randomnumber:
TypeError: '>' not supported between instances of 'builtin_function_or_method' and 'int'

这是代码

 #!/usr/bin/env python3

import random

win = False

randomnumber = random.randint(1,100)

print("I have picked a number between 1 and 100. Try and guess it!")

choice = input("Pick a number")

if choice == randomnumber:
  print("Good!!")
  Win = True
elif choice > randomnumber:
  print("Too high")
elif choice < randomnumber:
  print("Too Low")

if Win == True:
  exit

1 个答案:

答案 0 :(得分:0)

您需要将用户输入转换为整数,游戏才能正常运行。一种可行的方法是在开始检查数字是否太高或太低之前在代码中包括以下行:

choice = int(choice)

如果用户没有输入“ 1.2”之类的整数或根本不是数字的数字,则会抛出错误。

以下是您可以尝试的示例:

import random

win = False

randomnumber = random.randint(1, 100)

print("I have picked a number between 1 and 100. Try and guess it!")

choice = input("Pick a number\n")

choice = int(choice)

Win = False

if choice == randomnumber:
    print("Good!!")
    Win = True
elif choice > randomnumber:
    print("Too high")
elif choice < randomnumber:
    print("Too Low")

为了使游戏正常运行,您仍然需要添加某种形式的循环,以便用户可以随着时间的流逝更接近正确的猜测。