Python没有返回预期值

时间:2011-11-19 22:21:26

标签: python

我根本无法理解这里发生了什么。这个问题对我的作业很重要(学习编程所以我是初学者......我的英语也不是那么好,对不起)。

我正在尝试读取一个字符串......它可以是一个数字或一定数量的命令 我只是给出一个很小的例子,说明我正在尝试做什么以及出了什么问题。

    def validate():
        choice = str(input(">>> "))
        if (choice == "exit"):
            return 0 # should exit validate
        else:
            try:
                aux = int(choice) # Tries converting to integer
            except:
                print("Insert integer or exit")
                validate() # If it can't convert, prompts me to try again through
                           # recursivity
            else:
                return aux
    rezult = validate()
    print (rezult)

问题是这个小脚本会返回完全随机的东西。

如果“退出”,则返回“无” 如果第一次输入正确,则返回正确的数字 如果第一个输入是“错误”而第二个输入是正确的,那么它再次是“无”,我根本无法理解出现了什么问题......为什么它不想工作或我应该做什么(或者)。

3 个答案:

答案 0 :(得分:5)

如果您输入except块,函数validate()会使用递归调用来调用自身。当此调用返回时,它返回到调用函数的位置,即返回except块。此时忽略validate()的返回值,并且控件在没有命中return语句的情况下到达外部调用的末尾,因此隐式返回None

不要在这里使用递归。使用循环。

答案 1 :(得分:3)

使用raw_input代替input(除非您使用的是Python 3.x):

choice = raw_input(">>> ")

你错过了回归:

        except:
            print ("Insert integer or exit")
            return validate () # <<< here

另外,不要为此使用递归。改为使用循环。

答案 2 :(得分:1)

好的,决定听取并将递归部分更改为循环,谢谢你的帮助。 (立即行动)

     def validateChoice():
         condition = False
         while (condition == False):
             choice = str (input (">>> "))
             if (choice == "exit"):
                 return 0
             else:
                 try:
                     aux = int (choice)
                 except:
                     print ("Insert integer or 'exit'")
                 else:
                     condition = True
        return aux
相关问题