【问题标题】:Python Type Error: Error when trying to print string and integerPython 类型错误:尝试打印字符串和整数时出错
【发布时间】:2012-11-16 19:09:04
【问题描述】:

现在,我正在制作一个程序来计算如果您要向一群人演示并且您必须打印演示文稿的副本,您需要购买多少令纸。当我去运行程序时,它会出现:

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")

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

这是我的整个程序。

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")

【问题讨论】:

    标签: python string syntax integer operators


    【解决方案1】:

    首先&amp; 不是串联运算符(它是按位和运算符)- 那是+,但即使这样在strint 之间也不起作用...,您可以使用

    Python2.x

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

    Python 3.x

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

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

    print 'Total Sheets: {0} sheets'.format(total_Sheets)
    

    (注意:从 2.7+ 开始,您可以省略位置参数,如果需要,只需使用 {}

    【讨论】:

    • 啊,谢谢,我对 python 还很陌生,我所拥有的所有编程历史都是在 Visual Basic 中进行的。另外,感谢您的快速响应。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-18
    相关资源
    最近更新 更多