0

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

royce.lee
  • 19
  • 1
  • 5
  • You never break out of the while loop when the input is correct. Replace `pass` with `break` (or just an early return there). – 9769953 May 28 '18 at 04:48

2 Answers2

1

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.

Paula Thomas
  • 1,152
  • 1
  • 8
  • 13
  • One other thing: you'll need to change the pass to a break on the else branch of your if statement or, more efficiently, put the return statement there or you'll never get out of the infinite loop! – Paula Thomas May 28 '18 at 04:55
1

Instead of making starting global, return starting value to the caller. Use of global needs to be avoided if possible. Read why it is a bad design here. To implement in better way, your caller should be modified as:

starting = start_time()

Now starting time is obtained in starting.

Similarly,

ending = end_time()

Ending time is obtained in ending.

Also pass does not break out of the infinite while loop. It does nothing, but is used when a statement is required syntactically but the program requires no action. Use a break in-place of pass. It exits out of the innermost loop.

Read about the usage of break here.

Austin
  • 25,759
  • 4
  • 25
  • 48