0

I've typed up this code but I can't see what's wrong with it.

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

It keeps giving me "Can't convert 'int' object to str implicitly" even though I converted the integer into a string

Help out this noob please?

4

2 回答 2

1

尝试这个:

>>> number='5'
>>> if raw_input('enter number:')!=number:
...    print('Nope. The number I was thinking of was {}'.format(number))

或者:

>>> number=5
>>> if int(raw_input('enter number:'))!=number:
...    print('Nope. The number I was thinking of was {}'.format(number))

使用format 方法,您不需要进行显式类型转换来打印它,因为您没有连接两个字符串。不过,您需要确保在 if 语句中将字符串与字符串或 int 与 int 进行比较。

(如果您使用的是 Python 3,raw_input输入相同的功能...)

于 2013-02-21T22:28:10.683 回答
0

你只需要把你的块print里面。if

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

在您的原始代码中,即使您猜对了,它也会打印出来,这意味着该if块没有执行,因此number仍然是一个整数。

您还可以使用字符串格式来避免转换number为字符串。

print('Nope. The number I was thinking of was %d' % number)

drawk提到了较新的字符串格式化方法。

于 2013-02-21T22:56:15.583 回答