我在使用功能时遇到了一些麻烦。我写了一个函数:
def dep():
d = int(input("when did the employee depart? Please enter response in military time 0 - 2400 "))
while (d < 0 or d > 2400):
d= int(input("Please enter a valid number "))
return d
在以后的函数中,我想要值d。如此处所示:
def mealDep():
dep = dep()
if dep <= 700 and dep > 0:
我现在知道我不能只调用dep()并将其分配给变量,而是如何获取返回的值?
答案 0 :(得分:0)
我去清理了几个错误,并使其他事情更好地实践。除了用dep = ...
遮盖自己的功能外,还有其他一些事情,例如不能安全地强制转换用户输入。希望这会有所帮助。
def get_departure_time(): # verbosity is GOOD 99% of the time
while True:
# Get the raw input first
departure_time = input("When did the employee depart? Please enter response in military time 0 - 2400:")
# THEN validate. This prevents your code from breaking from type conversion
try:
departure_time = int(departure_time)
assert departure_time > 0 and departure_time < 2400
break # Breaks out of the infinite loop, and returns below
except (ValueError, AssertionError):
print("Please enter response in military time 0 - 2400.")
continue
return departure_time
def meal_dep(): # snek_case > camelback case
departure_time = get_departure_time()
if departure_time <= 700 and departure_time > 0:
...