我的随机数游戏轮系统的麻烦

时间:2018-02-25 22:18:35

标签: python

import random

rnd=0
guessesTaken = 0

print('Hello! What is your name?')
myName = input()

for i in range (10):
    print('---round' +str(rnd+1) +'---')

    number = random.randint(1, 20)
    print('Well, ' + myName + ', I am thinking of a number between 1 and 20.')

    while guessesTaken <= 5:
    ***~the error ^^^~***
        print('Take a guess.') 
        guess = input()
        guess = int(guess)

        guessesTaken = guessesTaken + 1

        if guess < number:
            print('Your guess is too low.') 

        if guess > number:
            print('Your guess is too high.')

        if guess == number:
            break

    if guess == number:
        guessesTaken = str(guessesTaken)
        print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')

    if guess != number:
        number = str(number)
        print('Nope. The number I was thinking of was ' + number)


    rnd=rnd+1

我试图在这个猜谜游戏中设置一个圆形系统,但是在第二轮之后它说'#34;嗯,艾哈,我想的是1到20之间的数字。&#34;有一个错误说

TypeError: '<=' not supported between instances of 'str' and 'int'

来自第15行。

1 个答案:

答案 0 :(得分:2)

当您说guessesTaken = str(guessesTaken)时,原始guessesTaken变量(整数)变为字符串。然后,当您第二次验证while循环条件guessTaken <= 5时,您正在将字符串整数进行比较。 。这不是支持的内容,因为您的错误是'<=' not supported between instances of 'str' and 'int'

正如评论中所述,解决方案是更好地理解字符串格式和打印用法。您不需要完全转换变量(意味着将整数转换为字符串)。

你可以做而不是......

guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')

这:

print('Good job, {} ! You guessed my number in {} guesses !'.format(myName, guessesTaken))

这样做,您只需按>打印变量,而不是将其转换为其他类型。如果您仍然按照自己的方式进行(顺便说一下,糟糕),您可以做...

guessesTaken = str(guessesTaken)
print('Good job, ' + myName + '! You guessed my number in ' + guessesTaken + ' guesses!')
guessesTaken = int(guessesTaken)