This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 1 year ago.
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?
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
if I have a code like this?
num1= input (" number goes here")
num2= input ("number goes here")
how can I make a simple equation work such as.
num3=num2+num1
print ("num3")
and when I do that it outputs
num2num3
I have tried things such as
int=(num1)
You need to convert num1 and num2 into int type because input gives you a str type.
num1 = int(input(" number goes here"))
num2 = int(input("number goes here"))
num3 = num1 + num2
print(num3)
The code is:Take 2 numbers from the user. Pass these two numbers to a function mathExp(). This function will calculate the sum of the cubes of the two numbers.
Return and print this value.
Function Structure:
int mathExp(int,int)
My code is:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(num1,num2):
print(num**3 + num**2, mathExp(num1,num2))
There is a lot wrong with this code:
First, you are calling the mathExp function IN itself. Thats recursion and I dont think that you want to do this.
Second, the parameters of the mathExp function are called num1 and num2. But in the function you use just num which doesnt exist.
So what you probably want to do is this:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(n1,n2):
return n1**3 + n2**3
print(mathExp(num1, num2))
Your mathExp function was wrong. Try this instead:
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
def mathExp(num1,num2):
ans = num1**3 + num2**3
return ans
cubes = mathExp(num1, num2)
print(cubes)
Try this code:
# take two number as input from the user
num1 = int(input("write a number: "))
num2 = int(input("write a number: "))
# define the function which calculate the sum of cubes of the input numbers
def mathExp(num1,num2):
result = num1**3 + num2**3
return result
# call the function with user input and print the result
print(mathExp(num1, num2))
Example:
write a number: 4
write a number: 7
407
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 5 years ago.
I was hoping on some input concerning the use of 'user inputted' arguments as variable value amounts to be used in a calculation within a function... this will no doubt be a very simple issue but I am new to python and so far my attempts at fixing it have been flawed.
The function is a simple calculation of adding two numbers together solely for the purpose of introducing new students to functions.
I have no issues with the function working as intended when I feed hard coded values as integers into the parameters (which are included in this example code)
but when I try to pass 'user input' argument values in when actually running the program the function simply concatenates the two values rather than adding them, this is (I presume) because the input values are in the format of a 'string'.
I have tried introducing 'int' statements after the 'input' statements within the argument variable code but this results in an error 'invalid literal for int()' I have also tried this at different points of the function code itself with no luck..... so how would I go about making sure the values are recognised as integers before or during calculation? Thanks
def getSum(num1, num2):
calc = num1 + num2
return calc
num1 = input("Type in your first number to add: ")
num2 = input("Type in your second number to add: ")
result1 = getSum(num1, num2)
answer = getSum(10, 5)
answer2 = getSum(155, 56668)
print(answer)
print(answer2)
print(result1)
int() should work correctly if the user only enters integer values - otherwise you have to wrap it with a try and catch block
try:
num1 = int(input("Type in your first number to add: "))
num2 = int(input("Type in your second number to add: "))
catch Exception as ex:
pass //do nothing
Just introduce int() for num1 and num2 in line2.
So the new code will be:
def getSum(num1, num2):
calc = int(num1) + int(num2)
return calc
num1 = input("Type in your first number to add: ")
num2 = input("Type in your second number to add: ")
result1 = getSum(num1, num2)
answer = getSum(10, 5)
answer2 = getSum(155, 56668)
print(answer)
print(answer2)
print(result1)
I am brand new to Python coding, so keep that in mind for the following problem. I am just learning the use of defining functions, arguments, and variables.
Define a function called ratioFunction that takes two numbers called num1 and num2 as arguments and calculates the ratio of the two numbers, and displays the results as (in this example num1 is 6, num2 is 3): ‘The ratio of 6 and 3 is 2’. The output after running the code should look like this:
Enter the first number: 6
Enter the second number: 3
The ratio of 6 and 3 is 2.
So here's what I've cooked up with my limited knowledge of coding and my total confusion over functions:
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
int(num1)
num2 = input('Enter the second number: ')
int(num2)
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
I am utterly confused, any help would be appreciated!
The problem is that you aren't capturing the results of the call to int.
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
int(num1) # this does nothing because you don't capture it
num2 = input('Enter the second number: ')
int(num2) # also this
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
Change it to:
def ratioFunction(num1, num2):
num1 = input('Enter the first number: ')
num1 = int(num1) # Now we are good
num2 = input('Enter the second number: ')
num2 = int(num2) # Good, good
ratio12 = int(num1/num2)
print('The ratio of', num1, 'and', num2,'is', ratio12 + '.')
ratioFunction(num1, num2)
Also, when you call ratioFunction(num1, num2) in your last line, this will be a NameError unless you have num1 and num2 definied somewhere. But honestly, this is totally unecessary because you are taking input. This function has no need for arguments. Also, there will be another bug when you print because you are using the + operator on ratio12 + '.' but ratio12 is an int and '.' is a string. Quick fix, convert ratio12 to str:
In [6]: def ratioFunction():
...: num1 = input('Enter the first number: ')
...: num1 = int(num1) # Now we are good
...: num2 = input('Enter the second number: ')
...: num2 = int(num2) # Good, good
...: ratio12 = int(num1/num2)
...: print('The ratio of', num1, 'and', num2,'is', str(ratio12) + '.')
...:
In [7]: ratioFunction()
Enter the first number: 6
Enter the second number: 2
The ratio of 6 and 2 is 3.
Although, likely, your function is suppose to take arguments, and you get input outside the function and pass it to it.
There are primarily 3 issues with your function:
The int division problem:
In Python3, dividing an int object by another int object can return a float.
For example:
In[] : a = 10
In[] : b = 3
In[] : a / b
Out[]: 3.3333333333333335
In[] : a // b # Fix 01: Specifying integer division to the interpreter
Out[]: 3
In[] : int(a / b)
Out[]: 3 # Fix 02: Type casting the float to int
Catching the return value of type casting num1 and num2.
You need to store the value returned by the int function on num1 and num2. Better yet, you can make this explicit when you ask the user for input.
In[] : num1 = int(input("Enter the first number :"))
In[] : num2 = int(input("Enter the second number :"))
Arguments in function ratioFunction's definition:
Since, you are prompting the user for input, it is totally point less to pass them as parameters beforehand. This is a poor design technique and can lead to further issues when you call ratioFunction from other scripts or functions.
Fix: Remove the arguments, and define it as
def ratioFunction()
Tip: I notice that you are using JAVA convention for naming Python function. I would suggest you read PEP8 Python coding style guide.
There are several minor things to fix in your function:
The function ratioFunction should not receive any parameters, because you are asking the user to input the values for num1 and num2 inside the function.
The statement "int(num1)" (without quotes) doesn't alter by itself the value of num1, it just returns the integer representation of num1. You should assign num1 the returned value, or create another variable for that purpose.
You're mixing strings and ints in the print statement (you cannot add a string and an integer). You could replace the + with a comma, but that's a bit ugly. There are several ways to achieve what you want, but I recommend you to use String formatting:
print('The ratio of {0} and {1} is {2}.'.format(num1, num2, ratio12))
If you have to consider non-integer divisions, use float (num1)/num2 to calculate it.
without using division(/) operations, as bellow you can get ration of 2 numbers :)
Output will be as follow:
coff num1 / num2
static int GCD(int p, int q)//find greatest common divisor
{
if (q == 0)
{
return p;
}
int r = p % q;
return GCD(q, r);
}
static string FindRatio(int num1, int num2)
{
string oran = "";
int gcd;
int quotient = 0;
while (num1 >= num2)
{
num1 = num1 - num2;
quotient++;
}
gcd = GCD(num1, num2);
//without using division finding ration of num1 i1
int i1 = 1;
while (gcd*i1 != num1)
{
i1++;
}
//without using division finding ration of num1 i2
int i2 = 1;
while (gcd * i2 != num2)
{
i2++;
}
oran = string.Concat(quotient, " ", i1,"/",i2);
return oran;
}
def RatioFunctions(num1, num2):
n1 = float(num1)
n2 = float(num2)
return n1/n2
I'm new to Python and I'm attempting to program a calculator. The problem is I can't find a way to make the variables num1 and num2 do the operation I have listed for them. All they do is concatenate the two numbers instead of performing the operation, any suggestions? Thanks.
letter = ()
class Calc():
print raw_input("What operation do you want to do?\n\tA) Addition\n\tB) Subtraction\n\ ")
num1 = raw_input("Please enter your first number: ")
num2 = raw_input("Please enter your second number: ")
if letter == 'A' or 'a':
print "The sum of", num1, "plus", num2, "equals"
print num1 + num2
elif letter == 'B' or 'b':
print "The difference of", num1, "minus", num2, "equals"
print num1 - num2
raw_input returns a string, so your two inputs are concatenated. You need to convert that input to a number before using it with numeric operators.
num1 = int(raw_input("Please enter your first number: "))
You can use either float or int to convert the input string to a number.
You also need to change
if letter == 'A' or 'a':
to
if letter == 'A' or letter == 'a':
You are using
raw_input()
which converts the input to strings.
If you want to add them together, you would like to use
num1 = float(num1)
before adding.
This is because you are doing string operations. raw_input returns a string, so you must manually convert it to an int or float using: float() or int().
Do this:
print int(num1) + int(num2) in order to print the numbers in their addition form.
I think this will do what you ask:
letter = raw_input("What operation do you want to do?\n\tA)
Addition\n\tB)Subtraction\n")
num1 = input("Please enter your first number: ")
num2 = input("Please enter your second number: ")
if letter == 'A' or 'a':
print "The sum of", num1, "plus", num2, "equals"
print num1 + num2
elif letter == 'B' or 'b':
print "The difference of", num1, "minus", num2, "equals"
print num1 - num2