Search code examples
pythonwhile-loopreturnglobaltry-except

Python While true, Try/Except, returning value


When I try to return a value after making a variable and putting a while True, try/except commands, the variable doesn't return the value. I am trying to globalize this "starting" so that it can be used.

def start_time():
    while True:
        try:
            starting = int(input("Please enter a starting hour(HH): "))
            if starting < 0:
                print("There are no negative hours!")
            elif starting > 24:
                print("There are only 24 hours in a day!")
            else:
                break
        except ValueError:
            print("Please enter in a correct format (HH)")
    return starting
def end_time():
    while True:
        try:
            ending = int(input("Please enter an ending hour (HH): "))
            if ending < starting:
                print("You can only plan a day!")
            elif ending < 0:
                print("There are only 24 hours in a day!")
            elif ending > 24:
                print("There are only 24 hours in a day!")
            else:
                break
        except ValueError:
            print("Please enter in a correct format (HH)")
    return ending

#obtain starting and ending time
start_time()
end_time()

#confirm starting and ending time

Thanks


Solution

  • Right, one amendment is needed to achieve your stated aim:

    replace:

    start_time()
    

    with

    starting = start_time()
    

    when a function is called that returns a value without an explicit place for that value to be put python in effect throws away the value.