-1

I am currently writing a program that receives input from users and processes them in separate functions. 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))

My problem with the code above is that it's really ugly. How am I able to process the data from users WITHOUT writing int() for every variable I used?

2 Answers2

0

No, you have to cast the input to integer at a point. Better approach will be to use int() on input() and .format():

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))
Wasif
  • 14,755
  • 3
  • 14
  • 34
0

You can use a map:

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

Or you can create a function named input_int(text) to avoid duplication:

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

Here is a better version of 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
Dorian Turba
  • 3,260
  • 3
  • 23
  • 67