【问题标题】:Python: Problems in calling the function from the while loopPython:从while循环调用函数的问题
【发布时间】:2016-09-05 09:34:42
【问题描述】:

我有一个 while 循环,它在每次迭代时调用函数 mainrt()。

if __name__ == "__main__":
    inp = sys.stdin.read()
    inpList = inp.split('\n')
    inpList.pop()
    for n in inpList:

        i = 0
        p = 0
        n  = int (n)
        while True:
            i += 1
            p = n*i
            if n == 0:
                print "INSOMNIA"
                break
            else:
                res = True
                res = mainrt(p)
                if res == False:
                    print p
                    break

还有mainrt()

def mainrt(n):
    #print n

    while True:
        rem = n % 10
        if rem in diMon:
            pass
        else:
            diMon.insert(rem,rem)

        if len(diMon) == 10:

            return False
            break

        n = n/10
        if n == 0:
            return True
            break
        else:
            continue

问题是当我从 stdin.read() 获取输入时,输入的第一行由函数正确处理,但输入的第二行按原样打印。它没有被函数处理 例子

INPUT
3
5

OUTPUT SHOLD BE
30
90

But instead I get
30
5

为什么函数第二次不处理输入??? 到目前为止没有运行时错误。

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    在您的mainrt 函数中,我没有看到您声明了diMon 列表,因此它看起来像是一个全局变量并且您没有清理该列表。这意味着您的mainrt 在第一次检查if len(diMon) == 10: 时返回False 以获取第二个输入。您应该在函数的开头或 mainrt 函数的开头声明 diMon 或在 while 循环体的末尾清除它。

    编辑: 现在我再次检查了你的代码,我建议你在for循环的开头声明diMon

    for n in inpList:
    
        diMon = []
        i = 0
        p = 0
        n  = int (n)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-19
      • 1970-01-01
      相关资源
      最近更新 更多