【问题标题】:How to call another functions returned value into a new function?如何将另一个函数的返回值调用到一个新函数中?
【发布时间】:2019-12-16 19:52:27
【问题描述】:

我只是遇到了一些功能问题。我写了一个函数:

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() 并将其分配给变量,但是如何获取返回的值呢?

【问题讨论】:

  • 虽然您不应该使用dep = dep(),因为这会重新分配名称dep,但您可以使用somevar = dep()。还要检查 return 语句的缩进。它目前不在函数中(尽管这可能只是 stackoverflow 显示问题)。
  • 我还建议捕获当用户输入文本而不是数字时将不可避免地发生的错误。
  • “我现在知道我不能只调用 dep() 并将其分配给变量”嗯,你当然可以这样做。
  • 抱歉,我认为我做不到。我想在网上找到它,但我从 user155 看到我不应该将变量命名为与函数相同的名称。

标签: python function return


【解决方案1】:

我去清理了几个错误,并让其他事情变得更好。除了使用 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:
        ...

【讨论】:

  • 那么只要第二个函数中的变量和第一个函数中的返回变量同名就行了?
  • @Jay,不,这与它无关。变量名对程序员来说是一种方便。如果你愿意,你可以写:foo = get_departure_time()not_departure_time = get_departure_time(),它也可以正常工作。
猜你喜欢
  • 1970-01-01
  • 2019-03-29
  • 2021-08-14
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-31
  • 1970-01-01
相关资源
最近更新 更多