为什么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')
答案 0 :(得分:5)
因为number
是一个整数。把它变成一个字符串:
print('Good Job, ' + myName + '! You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')
但是,使用str.format()
string formatting:
print('Good Job, {0}! You guessed my number {1} in {2} guesses!'.format(
myName, number, guessesTaken))
字符串格式为您转换输入;有关您拥有的格式选项的详细信息,请参阅Format String Syntax documentation。
答案 1 :(得分:1)
number
是一个整数。您无法添加整数和字符串,因为您收到的错误消息几乎肯定会告诉您。
使用str(number)
将其转换为字符串。
答案 2 :(得分:0)
问题是number
是一个整数。正如您收到的错误消息所述,您无法将整数和字符串一起添加。
您可以使用str(number)
将其转换为字符串,就像我在下面所做的那样。
这应该是:
print('Good Job, ' + myName + '! You guessed my number ' + str(number) + ' in ' + guessesTaken + ' guesses!')