0

I’m trying to find out whether there is a way to multiply two numbers that might be whole or decimal, from a user input, and print the answer, in Python. The code won’t run if I don’t have ‘int’ or ‘float’ in line 5, but that means that I can’t multiply a float by a whole number, or two whole numbers if float is being used. Is there a way that I can input a float and/or a whole number and it still run.

The code works fine if i type ‘multiplication()’ then ‘4 5’ and it prints 20, but if I type ‘multiplication’ and ‘4.5 5’ it displays the error message :

ValueError: invalid literal for int() with base 10: ‘4.5’


def multiplication():
  a = input()
  a.split() #splitting the 2 numbers you enter
  b,c = a.split() #assigning the 2 numbers values b and c
  d = int(b) * int(c) #multiplying b and c
  print(d) #printing the answer
  • `int()` parses a string that is in valid integer format to a Python integer. You should use `float()` for the prescribed behaviour. – Zoro Sep 08 '21 at 08:06
  • 1
    Does this answer your question? [How do I parse a string to a float or int?](https://stackoverflow.com/questions/379906/how-do-i-parse-a-string-to-a-float-or-int) – Zoro Sep 08 '21 at 08:08

1 Answers1

3

Just use float, it can handle int values as well:

def multiplication():
  a = input()
  b,c = a.split() #assigning the 2 numbers values b and c
  d = float(b) * float(c) #multiplying b and c
  print(d) #printing the answer
mozway
  • 194,879
  • 13
  • 39
  • 75