关于猜谜游戏的Python代码

时间:2015-10-27 13:14:07

标签: python python-3.x

我的代码有点问题,我试图制作一个猜猜游戏,实际上它来自一本书,但我无法弄清楚它有什么问题...

# A guess game program made in python
import random

guessesTaken = 0

print('Hello! What is your name, may i ask?')
myName = input()

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

while guessesTaken < 6:
    print('Take a guess..')
    guess = input()
    guess = int(guess)

    guessesTaken = guessesTaken + 1

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

    if guess > number:
        print('Your number is too high! guess lower or something!')

    if guess == number:
        break

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

    if guess != number:
            number = str(number)
            print('Nah, The number i was thinking of was ' + number)

这是它给我的错误..

Hello! What is your name, may i ask?
ygh
Well, ygh, I am thinking of a number between 1 and 20
Take a guess..
4
Your number guess is too low, guess again
Nah, The number i was thinking of was 7
Take a guess..
2
Traceback (most recent call last):
  File "C:/Users/Owner/Desktop/guess.py", line 19, in <module>
    if guess < number:
TypeError: unorderable types: int() < str()

Process finished with exit code 1

我使用Pycharm作为我的IDLE,我也在Windows上使用..

1 个答案:

答案 0 :(得分:0)

您的代码中很少有变化,而不是调用str您可以使用format()

# A guess game program made in python
import random

guessesTaken = 0

print('Hello! What is your name, may i ask?')
myName = input()

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

while guessesTaken < 6:
    print('Take a guess..')
    guess = input()
    guess = int(guess)

    guessesTaken += 1 # Instead of calling the variable itself then adding 1

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

    if guess > number:
        print('Your number is too high! guess lower or something!')

    if guess == number:
        print('Good job, {}! You guessed the right number in {} guesses!'.format(myName,guessesTaken))
        break # the beak goes here

    if guess != number:
        print('Nah, The number i was thinking of was {}'.format(number))

另外,您的break放置错误,因为它会在发送您想要的print之前执行,从而过早地结束您的代码。