我正在使用python3
创建文字游戏。
我的代码:
import random
secret = random.randint(1,99)
guess = 0
tries = 0
print (" AHOY! I'm the Dead Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries.")
while guess != secret and tries < 6:
guess = input ("What's yer guess?")
if guess < secret:
print ("Too low, ye scurvy dog!")
elif guess > secret:
print ("Too high, landlubber!")
tries = tries + 1
if guess == secret:
print ("Avast! Ye got it ! Found my secret, ye did!")
else:
print ("No more guesses! Better luck next time, matey!")
print ("The secret number was "), secret
跑完后,我得到了
TypeError: '<' not supported between instances of 'str' and 'int'
当我输入40
我不知道为什么会这样。
答案 0 :(得分:1)
Python 3.x&#39; input()
函数默认返回int
。为了获得类型int
的对象,您需要显式地键入它:
guess = int(input ("What's yer guess?"))
目前guess
是字符串变量,secret
是int,因此您无法使用运算符&#39;&lt;&#39;用string和int。
更新代码:
import random
secret = random.randint(1,99)
guess = 0
tries = 0
print (" AHOY! I'm the Dead Pirate Roberts, and I have a secret!")
print ("It is a number from 1 to 99. I'll give you 6 tries.")
while guess != secret and tries < 6:
guess = int(input ("What's yer guess?"))
if guess < secret:
print ("Too low, ye scurvy dog!")
elif guess > secret:
print ("Too high, landlubber!")
tries = tries + 1
if guess == secret:
print ("Avast! Ye got it ! Found my secret, ye did!")
else:
print ("No more guesses! Better luck next time, matey!")
print ("The secret number was "), secret