【问题标题】:When running a Python Program, the error "'return' outside function" pops up运行Python程序时,弹出错误“'return' outside function”
【发布时间】:2019-03-19 09:52:07
【问题描述】:

运行 Python 程序时,弹出错误“'return' outside 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)

有人可以帮忙吗?

【问题讨论】:

  • 这看起来根本不像 Python 代码。
  • @TFX,看看发布的答案是否有帮助?
  • @DirtyBit 非常感谢,它成功了。 c:

标签: python arrays python-3.x list


【解决方案1】:

Bad Indentation,你需要正确缩进你的函数定义,即:

def discount_ten():
    nondis=float[1.10,2.40,5.20,6.30,6.70]
    for i in nondis:
      return(nondis/10) 
    print(nondis)

注意:Python 遵循特定的缩进样式来定义 代码,因为 Python 函数没有任何明确的开始或结束 花括号表示函数的开始和停止,它们 必须依赖这个缩进。

EDIT(针对您想要的输出进行修复):

使用列表存储结果,循环中不需要return,因为这将退出循环并在第一次迭代时仅打印0.11000000000000001。此外,使用round() 舍入到最接近的所需小数位:

def discount_ten():
    nondis = [1.10,2.40,5.20,6.30,6.70]
    res = []                      # empty list to store the results
    for i in nondis:
      res.append(round(i/10, 2))  # appending each (rounded off to 2) result to the list
    return res                    # returning the list

print(discount_ten())

输出

[0.11, 0.24, 0.52, 0.63, 0.67]

【讨论】:

    【解决方案2】:

    在 Python 中,缩进是代码的重要组成部分。每个块增加一级缩进。要定义一个函数,您必须将函数的每一行缩进相同的量。

    def discount_ten():
        distcount_list = []
        nondis = [1.10,2.40,5.20,6.30,6.70]
        for i in nondis:
            distcount_list.append(round(i/10,2))
        return distcount_list
    print(discount_ten())
    

    【讨论】:

      【解决方案3】:

      我认为你的函数没有正确缩进,看看下面的代码:

      此函数打印愿望输出:

      def discount_ten():
         nondis=[1.10,2.40,5.20,6.30,6.70]
         for i in nondis:
           print(i/10)
      

      此函数返回所需输出的列表:

      def discount_ten():
          nondis=float[1.10,2.40,5.20,6.30,6.70]
          disc_ten=[]
          for i in nondis:
             disc.append(i/10)
          return disc
      

      注意:代码块(函数体、循环等)以缩进开始,以第一个未缩进的行结束。缩进量由您决定,但必须在整个块中保持一致。

      --

      【讨论】:

      • 非常感谢,程序运行了,但打印出“无”
      • 请分享你想要的输出
      • 0.11,0.24,0.52,0.63,0.67
      • 非常感谢您的帮助:)
      猜你喜欢
      • 2021-03-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 2018-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多