【问题标题】:Functions returning issue函数返回问题
【发布时间】:2013-06-12 02:28:06
【问题描述】:

我目前正在编写一个代码,该代码要求用户输入一个整数并计算该整数所具有的除数。我已经完成了代码,但被困在“返回部分”上。 这是我到目前为止所得到的:

def findDivisors(number):
    decrease = number
    count = 0
    while ( decrease >= 1):
        if ( number%decrease == 0 ):
            count=count+1
    decrease=decrease-1

def main(count):
    number = int(input("Please enter a positive integer : "))
    print(count)

main()

我尝试返回“数字”和“计数”,但似乎无法正常工作。 有什么建议么 ? 顺便说一句,我使用的是 Python 3.3.1

【问题讨论】:

  • 您在底线对 main 的调用与之前定义的任何函数都不匹配。您的 findDivisors() 函数将进入无限循环,因为您在 while 循环中减少了 reduction 变量;因此对于任何大于 0 的数字,都会发生无限循环。有关其他修复,请参阅@Simon 的第一个答案

标签: python python-3.x return


【解决方案1】:
  1. 你需要return count在函数findDivisors()的末尾。
  2. findDivisors() 中的缩进似乎不正确(decrease=decrease-1 的缩进应该与if 语句的第一行一样多。
  3. 我看不出您有任何理由希望 count 作为 main() 函数的参数,尤其是当您在没有任何参数的情况下调用 main() 时。
  4. 代码中没有证据表明您实际上正在调用函数findDivisors()。我建议用print(findDivisors(number)) 替换print 调用。

【讨论】:

  • 完美!感谢您的详细回答。
猜你喜欢
  • 1970-01-01
  • 2013-03-02
  • 2016-01-08
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2011-03-15
  • 2011-10-05
  • 2020-09-09
相关资源
最近更新 更多