为什么python不返回任何值?

2024-04-26 22:10:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从用户那里得到小时和分钟,但是当我输入一个字母数字,一个超出用户允许范围的数字时,用户返回一个None类型的值。我只是想从用户那里得到号码。我知道解决办法是显而易见的,但由于某种原因我想不出来。你知道吗

def get_hours():
        h = input("Hour:")
        try:
                if len(h) == 0:
                        return 0
                else:
                        h = int(h)
                        if 0 <= h <= 24:
                                print(h)
                                print(type(h))
                                return h
                        else:
                                print("Enter Hours between 0 and 24")
                                get_hours()
        except ValueError:
                print("Enter Hour example = 16")
                get_hours()

def get_mins():
        m = input("Minutes:")
        try:
                if len(m) == 0:
                        return 0
                else:
                        m = int(m)
                        if 0 <= m <= 60:
                                print(m)
                                print(type(m))
                                return m
                        else:
                                print("Enter minutes between 0 and 60")
                                get_mins()

        except ValueError:
                print("Enter Minutes example = 23")
                get_mins()

def get_activity():
    flag = True
    while flag:
        ui = input("Enter a brief summary of what you will be doing? \n:")
        if len(ui) == 0:
            flag = True
        else:
            return ui

def main():
    data = []
    time = []
    activity = []
    hour = get_hours()
    print(type(hour))
    print("Hours: " +str(hour))
    while hour == None:
            hour = get_hours()

    mins = get_mins()
    print(type(mins))
    print("Mins: " + str(mins))
    while mins == None:
            mins = get_mins()
main()

这就是我想要的:

Hours: 10

Minutes: 53

这是当输入以下输入时得到的结果

Hour:1a

Enter Hour example = 16

Hour:231

Enter Hours between 0 and 24

Hour:2

2

<class 'int'>

<class 'NoneType'>

Hours: None

Hour:2a

Enter Hour example = 16

Hour:2

2

<class 'int'>

Hour:2a

Enter Hour example = 16

Hour:2

2

<class 'int'>

Hour:2

2

<class 'int'>

Minutes:2a

Enter Minutes example = 23

Minutes:222

Enter minutes between 0 and 60

Minutes:2a

Enter Minutes example = 23

Minutes:2

2

<class 'int'>

<class 'NoneType'>

Mins: None

Minutes:2

2

<class 'int'>

Tags: nonegetreturnifexampleelseclassint
1条回答
网友
1楼 · 发布于 2024-04-26 22:10:48

所有路径都需要指向您自己的return语句,这样您就不会得到None。你知道吗

例如,这里没有返回值。你知道吗

else:
    print("Enter Hours between 0 and 24")
    get_hours()
    # return None  # this is implicit

建议:使用适当的循环,而不是递归,但如果这样做,则应返回递归结果。你知道吗

else:
    print("Enter Hours between 0 and 24")
    return get_hours()  # this is explicit

相关问题 更多 >