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

1
  • You never break out of the while loop when the input is correct. Replace pass with break (or just an early return there). Commented May 28, 2018 at 4:48

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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!
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.