-5

为什么 Python 在未注释且另一行不存在时不喜欢已注释的打印行?

# This is a guess the number game
import random

guessesTaken = 0

myName = input('Hi there! What is your name?')


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


while guessesTaken < 6:
    guess = int(input('Try and guess what it is!')) # There are 4 spaces in front of print.
    # guess = int(input ())


    guessesTaken = guessesTaken + 1

    if guess < number:
        print('Your guess is too low') # There are 8 spaces in front of print.

    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 ' + number + ' in ' + guessesTaken + ' guesses!')  
    print('Good Job, ' + myName + '!  You guessed my number in ' + guessesTaken + ' guesses!')
if guess != number:
    number = str(number)
    print('I am sorry.  The number I was thinking of was ' + number + ' Thanks for playing, though.')   

input('\n\nPress Enter to exit')
4

3 回答 3

5

因为number是整数。也把它变成一个字符串:

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

str.format()但是,使用字符串格式会更好:

print('Good Job, {0}!  You guessed my number {1} in {2} guesses!'.format(
    myName, number, guessesTaken))

字符串格式化为您转换输入;有关您拥有的格式选项的更多详细信息,请参阅格式字符串语法文档。

于 2013-10-16T16:54:02.603 回答
1

number是一个整数。您不能添加整数和字符串,因为您收到的错误消息几乎肯定会告诉您。

使用 . 将其转换为字符串str(number)

于 2013-10-16T16:55:15.610 回答
0

问题是它number是一个整数。正如您收到的错误消息所述,您不能将整数和字符串相加。

str(number)您可以像我在下面所做的那样将其转换为字符串。

这应该是:

print('Good Job, ' + myName + '!  You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')  
于 2013-10-17T13:13:32.900 回答