python程序问题(TypeError: cannot concatenate 'str' and 'int' objects)

原题是要求运行时是这样的:Pleasethinkofanumberbetween0and100!Isyoursecretnumber50?Enter'h'toindica... 原题是要求运行时是这样的:
Please think of a number between 0 and 100!
Is your secret number 50?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l(这个 l 以及下面的 h 和 c 是自己手动输入的)
Is your secret number 75?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. l
Is your secret number 87?
Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. c
Game over. Your secret number was: 87

然后我的程序如下:
print "Please think of a number between 0 and 100!"
high=100
low=0
p=(low + high) / 2
print "Is your secret number" + p +"?"
i=raw_input("Enter 'h' to indicate the guess is too high.Enter 'l' to indicate the guess is too low. Enter 'c'to indicate I guessed correctly.")
while i!='c':
if i=='h':
high = p
elif i=='l':
low = p
else :
print "Sorry, I did not understand your input."
p=(high + low) / 2
print "Is your secret number" + p +"?"
i=raw_input("Enter 'h' to indicate the guess is too high.Enter 'l' to indicate the guess is too low. Enter 'c'to indicate I guessed correctly.")

print "Game over. Your secret number was:"+ p

可是我运行时出了错误:TypeError: cannot concatenate 'str' and 'int' objects

ERROR: Failing on first line.

我不懂,求问我要怎么改呢(T^T)
展开
 我来答
Robeanithe
推荐于2018-02-22 · TA获得超过172个赞
知道答主
回答量:33
采纳率:0%
帮助的人:40.9万
展开全部
Python allow to concatenate strings by '+', but here, your p is an integer.

So, to solve it, you can use either of these:

1. print 'Is your secret number " + str(p) + "?"
2. print 'Is your secret number %d?"%p
(for multiple integers, you can '%d %d %d'%(num1, num2, num3)
3. print 'Is your secret number {0}?".format(p)

I personally like the second one best. It's more of c style, doesn't it?
ZetaChow
2013-11-01 · TA获得超过141个赞
知道答主
回答量:33
采纳率:100%
帮助的人:31.9万
展开全部
python 组合字符串时不要用 a+b ,

应该是 print "Game over. Your secret number was:%s" % (p,)

全部改成这个模式
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
卷心菜92
2019-02-03 · TA获得超过840个赞
知道小有建树答主
回答量:860
采纳率:0%
帮助的人:465万
展开全部
print "Is your secret number" + p +"?"
前面是string,p是int,不能相加,要用
print "Is your secret number" + str(p) +"?"
可以加qq讨论
追问
呃……我很少上QQ……其实后来这道题我想出来了,我也是像你这样写的……只不过3楼的亲写的更完整……抱歉啦……
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式