在Python上打印变量时出现语法错误

2024-03-29 09:33:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python代码出现语法错误。IDLE没有给出错误可能在哪里的提示。在

我正在用覆盆子皮3运行python3。在

inches = input "How many inches?"
cm = inches*2.54
print "That is" {} "centimeters.".format(cm)

我希望输出能问我要转换多少英寸。然后它会声明它等于的厘米值。在

相反,它会弹出一个窗口,显示“语法错误”,而没有其他信息。在


Tags: 代码input覆盆子thatis错误cmpython3
3条回答

正确的写法是

inches = input("How many inches?")
cm = inches*2.54
print("That is %f centimeters" % (cm))

%意味着你将在这里插入一个值,在id后面的字符,你要在这里插入的变量的类型,我用%f表示浮点,你也可以用%s作为字符串。在

inches = input("How many inches?")
cm = inches*2.54
print("That is" {} "centimeters.".format(cm))

必须将字符串括在括号内。在

inches = input("How many inches?")

但这还不够,你需要一个数来执行乘法运算。所以用float()覆盖你的input()代表浮点数,或者{}代表整数。在

^{pr2}$

与Python2不同,在Python3中,print()是一个内置函数,它的参数必须放在括号内。另外,方括号{}必须用引号括起来。在

print("That is {} centimeters.".format(cm))

所以您的代码可能看起来像:

inches = int(input("How many inches?")) # or inches = float(input("How many inches?")) 
cm = inches*2.54
print("That is {} centimeters.".format(cm))

相关问题 更多 >