运行Python程序时,弹出错误“'return' external function”

运行Python程序时,弹出错误“'return' external function”。


我正在尝试制作一个浮点数列表并返回一个列表,其中每个元素都有 10% 的折扣。


def discount_ten():

nondis=float[1.10,2.40,5.20,6.30,6.70]

for i in nondis:

  |return(nondis/10) #<- "|" is the red highlighting.#

print(nondis)

有人可以帮忙吗?


九州编程
浏览 258回答 3
3回答

梦里花落0921

缩进错误,您需要正确缩进您的函数定义,即:def discount_ten():&nbsp; &nbsp; nondis=float[1.10,2.40,5.20,6.30,6.70]&nbsp; &nbsp; for i in nondis:&nbsp; &nbsp; &nbsp; return(nondis/10)&nbsp;&nbsp; &nbsp; print(nondis)注意:Python 遵循特定的缩进风格来定义代码,因为 Python 函数没有像花括号那样显式的开始或结束来指示函数的开始和结束,所以它们必须依赖于这种缩进。编辑(固定为您想要的输出):使用列表来存储结果,您不需要return循环中的 a,因为这将退出循环并仅0.11000000000000001在第一次迭代时打印。此外,使用 around()舍入到最接近的所需小数位:def discount_ten():&nbsp; &nbsp; nondis = [1.10,2.40,5.20,6.30,6.70]&nbsp; &nbsp; res = []&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # empty list to store the results&nbsp; &nbsp; for i in nondis:&nbsp; &nbsp; &nbsp; res.append(round(i/10, 2))&nbsp; # appending each (rounded off to 2) result to the list&nbsp; &nbsp; return res&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # returning the listprint(discount_ten())输出:[0.11, 0.24, 0.52, 0.63, 0.67]

慕雪6442864

我认为您的函数没有正确缩进,请查看以下代码:此函数打印期望输出:def discount_ten():&nbsp; &nbsp;nondis=[1.10,2.40,5.20,6.30,6.70]&nbsp; &nbsp;for i in nondis:&nbsp; &nbsp; &nbsp;print(i/10)此函数返回所需输出的列表:def discount_ten():&nbsp; &nbsp; nondis=float[1.10,2.40,5.20,6.30,6.70]&nbsp; &nbsp; disc_ten=[]&nbsp; &nbsp; for i in nondis:&nbsp; &nbsp; &nbsp; &nbsp;disc.append(i/10)&nbsp; &nbsp; return disc注意:代码块(函数体、循环等)以缩进开始,以第一个未缩进的行结束。缩进量由您决定,但它必须在整个块中保持一致。

开心每一天1111

在 Python 中,缩进是代码的重要组成部分。每个块添加一级缩进。要定义函数,您必须将函数的每一行缩进相同的数量。def discount_ten():&nbsp; &nbsp; distcount_list = []&nbsp; &nbsp; nondis = [1.10,2.40,5.20,6.30,6.70]&nbsp; &nbsp; for i in nondis:&nbsp; &nbsp; &nbsp; &nbsp; distcount_list.append(round(i/10,2))&nbsp; &nbsp; return distcount_listprint(discount_ten())
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python