这段代码可以在终端中运行,但在atom中不能运行。我在return print行上得到一个语法错误。很抱歉,如果这是显而易见的,我是编程新手。
#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))发布于 2020-09-15 13:59:48
print语句只是将其内部的内容输出到stdout,但它仍然返回一个None值。尝试在终端中执行x = print('Hello world!')。您将看到,尽管在终端中输出了Hello world!,但x的值仍然是None。
因此,您的代码与只使用print而不返回任何内容是一样的。我不确定为什么Atom指出这是一个语法错误,但这样做肯定不是常规做法。
发布于 2020-09-15 14:01:03
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))或者你可以以list /tuple/dict的形式返回:
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))发布于 2020-09-15 14:11:31
答案由@VPfB在问题本身的评论中给出。print是Python语言中的一个函数,3...it返回值,因此return print("foo")是一个有效的语句。但是在Python2中,function...it是一个语句,而不是一个不返回值的语句。尝试像在return print("foo")中那样处理它,会导致解释器出现语法错误。
这就是为什么@JaydeepDevda询问操作员他正在运行哪个版本的Python。我认为他很可能在终端上运行Python3,但在Atom中运行Python2。这可以解释行为上的差异。
https://stackoverflow.com/questions/63895881
复制相似问题