有没有办法从def函数获取输入?

时间:2020-09-04 19:24:27

标签: python

我想知道是否有可能从def函数中获取唯一的输入。

def choose():
while True:
    try:
        pick = float(input("Enter any number that isn't 0 "))
        if pick != 0:
            break
        else:
            pick = float(input("Try again! Enter any number that isn't 0 "))
    except ValueError:
        print("Sorry, I didn't understand that.")
        continue
    else:
        break
  choose()

我会尽量保持清晰。您可以从pick处获取choose()的输入并将其存储在其他位置吗?就像输入完所需的电话号码一样。

您可以运行:

print(pick + 15)

,否则您根本无法接受来自choose()的输入。我只想知道。如果是这样,原因是我什至不知道该怎么做。因此,我很感谢您的建议。

1 个答案:

答案 0 :(得分:0)

您不能从函数外部访问局部变量。该函数应返回该值,您可以将其分配给另一个变量。

def choose():
    while True:
        try:
            pick = float(input("Enter any number that isn't 0 "))
            if pick != 0:
                return pick
            else:
                print("Try again. The number has to be non-zero!")
        except ValueError:
            print("Sorry, I didn't understand that.")

choice = choose()
print(choice + 15)

您也不应该在else:块中要求输入,因为它将在循环重复时再次询问。只需在其中打印错误消息,而无需阅读输入。

您不需要continue语句,因为循环会自动继续,除非重复条件变为假(while True:永远不会发生)或执行break或{{ 1}}语句退出循环。