Python类型错误:尝试打印字符串和整数时出错

时间:2012-11-16 19:09:05

标签: python string syntax integer operators

现在,我正在制作一个计划,如果你正在向一群人做演示而你必须打印你的演示文稿的副本,你必须找到多少纸。当我开始运行程序时,它会出现:

Traceback (most recent call last):
File "C:/Users/Shepard/Desktop/Assignment 5.py", line 11, in <module>
print ("Total Sheets: " & total_Sheets & " sheets")
TypeError: unsupported operand type(s) for &: 'str' and 'int'
>>> 

我要做的是:

print ("Total Sheets: " & total_Sheets & " sheets")
print ("Total Reams: " & total_Reams & " reams")

我不应该使用&amp;运算符将字符串和整数类型与print结合起来?如果没有,我做错了什么?

这是我的整个计划。

ream = 500
report_Input = int (input ("How many pages long is the report?"))
people_Input = int (input ("How many people do you need to print for? -Automatically prints five extras-"))


people = people_Input + 5

total_Sheets = report_Input * people
total_Reams =((total_Sheets % 500) - total_Sheets) / people

print ("Total Sheets: " & total_Sheets & " sheets")
print ("Total Reams: " & total_Reams & " reams")

编辑:发布之后我发现Jon Clements的答案是最好的答案,而且我还发现我需要输入if语句才能使其正常工作。这是我完成的代码,感谢所有帮助。

ream = 500
report_Input = int (input ("How many pages long is the report?"))
people_Input = int (input ("How many people do you need to print for? -Automatically prints five extras-"))


people = people_Input + 5

total_Sheets = report_Input * people
if total_Sheets % 500 > 0:
    total_Reams =(((total_Sheets - abs(total_Sheets % 500))) / ream)+1
else:
    total_reams = total_Sheets / ream


print ("Total Sheets:", total_Sheets, "sheets")
print ("Total Reams:", total_Reams, "reams")

1 个答案:

答案 0 :(得分:4)

首先&不是连接运算符(它是按位和运算符) - 即+,但即使这在str和{{1}之间也不起作用} ...,你可以使用

Python2.x

int

Python 3.x

print 'Total Sheets:', total_Sheets, 'sheets'

或者,您可以使用字符串格式:

print ('Total Sheets:', total_Sheets, 'sheets')

(注意:从2.7+开始,您可以省略位置参数,如果需要,只需使用print 'Total Sheets: {0} sheets'.format(total_Sheets)