How to pass string input as integer arguments?

Viewed 6372

I wanted to do the following simple calculation by passing values for the parameters num1 and num2 from input() methods.

I tried following code:

def add(num1, num2):
    return num1 * num2

num1 = input('Enter number1: ')
num2 = input('Enter number2: ')

print(add(num1, num2))

But it is showing the following error when it is run (After input num1 and num2):

TypeError: can't multiply sequence by non-int of type 'str'

Can somebody please explain where did I go wrong and how to convert an input string to the integer type?

4 Answers

input() will returns a string, you have to convert the string to a int or float, you can test if the input is a valid number.

isnumeric() will return true if all chars in the string are numeric ones and the string is not empty.

Note: i renamed the function to multiply because this is not adding ...

def multiply(num1,num2):
    return num1*num2

inp1=input('Enter number1: ')
inp2=input('Enter number2: ')

if inp1.isnumeric() and inp2.isnumeric():
    num1 = int(inp1)
    num2 = int(inp2)
    print(multiply(num1,num2))
else:
    print("Atleast one input is not numeric")

You can try this:

def add(num1, num2):
    return num1 * num2

num1 = int(input('Enter number1: '))
num2 = int(input('Enter number2: '))

print(add(num1, num2))

The input function stores the input as a string and so what is happening in your code is that you are entering two integers but they are being stored as strings. You cannot multiply two strings. All you need to do is convert the input strings to integers by using the [int()][2] function. If you want to multiply floats, you can use the [float()][3] function in place of the int() function. You can also convert the strings to integers or floats once you have passed them into the function. Something like this:

def add(num1, num2):
    return int(num1) * int(num2)

num1 = input('Enter number1: ')
num2 = input('Enter number2: ')

print(add(num1, num2))

input (in Python 3) returns a str which is seen as text and not a number. If you want to multiply (or add) numbers, you must first parse the strings as numbers.

Sometimes this will fail as well. If you're assuming the input is always going to be a valid number, you can convert a string using:

float("3.1415926")

You can use this in your code with:

def add(num1,num2):
    return num1*num2

num1=float(input('Enter number1: '))
num2=float(input('Enter number2: '))

print(add(num1,num2))

To avoid floating point errors, you can print/display the float using an f-string (added in Python 3.6).

def add(num1,num2):
    return num1*num2

num1=float(input('Enter number1: '))
num2=float(input('Enter number2: '))

print(f"{add(num1,num2):.2f}")
def mul(num1,num2):
    return(num1*num2)

inp1 = input('Enter number1:')
inp2 = input('Enter number2:')

num1 = int(inp1)
num2 = int(inp2)

print(mul(num1,num2))
Related