这个Python游戏代码有什么问题?

Roy*_*yce 4 python

import random

secret = random.randint (1,99)
guess = 0
tries = 0

print ("AHOY! I'm the Dread 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, landrubber!")
    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)
Run Code Online (Sandbox Code Playgroud)

我一直收到这个错误:如果猜测<secret:TypeError:unorderable类型:str()<int()

Jus*_*ini 12

guess = input ("What's yer guess? ")
Run Code Online (Sandbox Code Playgroud)

通话input给你回复string,而不是int.然后,当您guess使用比较时<,您需要一个int比较数值.尝试做一些事情:

try:
    guess = int(input("What's yer guess? "))
except ValueError:
    # Handle bad input
Run Code Online (Sandbox Code Playgroud)


Chi*_*chi 6

因为Python是强类型的,所以你无法比较字符串和int.你得到的回报input()str不是int.因此,您需要在比较之前将其转换str为a int.

guess = int(input("What's yer guess"))
Run Code Online (Sandbox Code Playgroud)

您还应该处理输入无法转换为可能时抛出的异常int.所以,代码变成:

try:
    guess = int(input("What's yer guess"))
except ValueError:
    print ('Arrrrr... I said a number ye lily-livered dog')
Run Code Online (Sandbox Code Playgroud)

另外,input()至少在Python 2.x中是不安全的.这是因为input()接受任何有效的Python语句.raw_input()如果您使用的是Python 2.x,则应该使用.如果您使用的是Python 3,请忽略这一点.

try:
    guess = int(raw_input("What's yer guess"))
except ValueError:
    print 'Arrrrr... I said a number ye lily-livered dog'
Run Code Online (Sandbox Code Playgroud)