![](/img/trans.png)
[英]How to correct Syntax error with my elif, if statement. what am I doing wrong?
[英]I get syntax error on my print statement in my function. I don't know what I am doing wrong
此代码适用于终端但不适用于原子。 我在返回打印行上收到语法错误。 对不起,如果很明显,我是编程新手。
#returns footage stretched
material_feet = input('Material Feet: ')
material_inches = input('Material Inches: ')
actual_feet = input('Actual Feet: ')
actual_inches = input('Actual Inches: ')
def Stretch(material_feet, material_inches, actual_feet, actual_inches):
material_total = material_feet * 12 + material_inches
actual_total = actual_feet * 12 + actual_inches
amount_stretched = (actual_total - material_total) * 12 / actual_total
difference = divmod((actual_total - material_total), 12)
return print('Material stretched total of ' + str(difference) + ' and stretched ' + str(amount_stretched) + ' per foot.')
Stretch(int(material_feet), int(material_inches), int(actual_feet), int(actual_inches))
print
语句只是将其中的内容输出到stdout
,但它仍然返回None
值。 尝试在终端中执行x = print('Hello world!')
。 您会在Hello world!
看到这一点Hello world!
在终端打印, x
的值仍然是None
。
因此,您的代码与仅使用print
而不返回任何内容相同。 我不确定为什么 Atom 将其指出为语法错误,但这样做肯定不是惯例。
return以表达式列表(或 None)作为返回值离开当前函数调用。 所以你不能在 return 语句中使用 print 而不是它,你可以像下面的代码一样使用。
def Stretch(material_feet, material_inches, actual_feet, actual_inches):
return str(difference),str(amount_stretched)
diff , amt_str = Stretch(int(material_feet), int(material_inches), int(actual_feet), int(actual_inches))
或者你可以以列表/元组/字典的形式返回:
def Stretch(material_feet, material_inches, actual_feet, actual_inches):
return [str(difference),str(amount_stretched)]
LIST = Stretch(int(material_feet), int(material_inches), int(actual_feet), int(actual_inches))
@VPfB 在对问题本身的评论中给出了答案。 print
是 Python 3 中的一个函数……它返回一个值,因此return print("foo")
是一个有效的语句。 但是在 Python 2 中,print 是一个语句而不是一个函数……它不返回值。 试图像对待它一样对待它,就像return print("foo")
,会导致解释器出现语法错误。
这就是为什么@JaydeepDevda 询问 OP 他正在运行哪个版本的 Python。 我认为他很可能在终端运行 Python 3,但在 Atom 中运行 Python 2。 这将解释行为的差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.