Python: 如何从输入函数接收值并将它们作为整数工作?

Python: How receive values from an input function and have them working as an integer?

我目前正在编写一个程序来接收用户的输入并在单独的函数中处理它们。 MRE:

def prompt_user():
    money1 = input("insert a value")
    money2 = input(" insert another value")
    return money1, money2

def add(money1, money2):
    cash = int(money1) + int(money2)
    return cash

two_values = prompt_user()
total = add(*two_values)
print("you have "+ str(total))

我对上面代码的问题是它真的很难看。我如何能够在不为我使用的每个变量编写 int() 的情况下处理来自用户的数据?

不,您必须在某个点将输入转换为整数。更好的方法是在 input().format():

上使用 int()
def prompt_user():
    money1 = int(input("insert a value"))
    money2 = int(input(" insert another value"))
    return money1, money2

def add(money1, money2):
    cash = money1 + money2
    return cash

two_values = prompt_user()
total = add(*two_values)
print("you have {}".format(total))

您可以使用 map:

def prompt_user():
    money1 = input("insert a value")
    money2 = input(" insert another value")
    return map(int, (money1, money2))

或者您可以创建一个名为 input_int(text) 的函数以避免重复:

def input_int(text=""):
    return int(input(text))

def prompt_user():
    money1 = input_int("insert a value")
    money2 = input_int(" insert another value")
    return money1, money2

这是 input_int(text) 的更好版本:

def input_int(text=""):
    while True:
        try:
            res = int(input(text))
            break
        except ValueError:
            print("The input must be an integer")
    return res