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
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.
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.