我已经开始了python的教程,之前没有编程经验。目前,我正在做练习5,在那里我必须将英寸转换成厘米或反之,并发生一个问题。我使用的是2.12的python,暂时不打算换成本教程。我非常恼火和沮丧,为什么这个简单的问题发生,我不能找出原因。下面是代码。
centimeter = 1
inch = centimeter * 2,54
converted_value = 10 * inch
print "i decided to convert 10 inches to centimeters. Results are astonishing. %d " % converted_value
我在Windows powershell中运行了这个练习 它给我的报告是这样的:
"Traceback (most recent call last):
File "vaja5.py", line 28, in <module>
print "i decided to convert 10 inches to centimeters. Results are astonishing. %d" % converted_value
TypeError: not all arguments converted during string formatting"
先谢谢你的帮助 我真的很感激
centimeter * 2,54
创建一个2个元素的元组 (2,54)
. 当你试图为你的字符串提供2个参数时,问题就会发生(元组被解压),而你的字符串只有一个占位符(%d
).
改为:
inch = centimeter * 2,54
改为:
inch = centimeter * 2.54
你有一个错别字。
inch = centimeter * 2,54
应该是
inch = centimeter * 2.54
你原来的语法阐述为
inch = (centimeter * 2, 54)
所以你最终分配了一个元组,这导致了格式错误。