Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass string input as integer arguments? [duplicate]

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?

like image 656
Indi Avatar asked Dec 06 '25 14:12

Indi


2 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")
like image 136
Fabian Avatar answered Dec 09 '25 04:12

Fabian


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))
like image 41
Sultan Singh Atwal Avatar answered Dec 09 '25 03:12

Sultan Singh Atwal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!