This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 4 years ago.
I am trying to create a python program that uses user input in an equation. When I run the program, it gives this error code, "answer = ((((A*10A)**2)(B*C))*D**E) TypeError: unsupported operand type(s) for ** or pow(): 'int' and 'str'". My code is:
import cmath
A = input("Enter a number for A: ")
B = input("Enter a number for B: ")
C = input("Enter a number for C: ")
D = input("Enter a number for D: ")
E = input("Enter a number for E: ")
answer = ((((A*10**A)**2)**(B*C))*D**E)
print(answer)`
The input() function returns a string value: you need to convert to a number using Decimal:
from decimal import Decimal
A = Decimal(input("Enter a number for A: "))
# ... etc
But your user might enter something that isn't a decimal number, so you might want to do some checking:
from decimal import Decimal, InvalidOperation
def get_decimal_input(variableName):
x = None
while x is None:
try:
x = Decimal(input('Enter a number for ' + variableName + ': '))
except InvalidOperation:
print("That's not a number")
return x
A = get_decimal_input('A')
B = get_decimal_input('B')
C = get_decimal_input('C')
D = get_decimal_input('D')
E = get_decimal_input('E')
print((((A * 10 ** A) ** 2) ** (B * C)) * D ** E)
The compiler thinks your inputs are of string type. You can wrap each of A, B, C, D, E with float() to cast the input into float type, provided you're actually inputting numbers at the terminal. This way, you're taking powers of float numbers instead of strings, which python doesn't know how to handle.
A = float(input("Enter a number for A: "))
B = float(input("Enter a number for B: "))
C = float(input("Enter a number for C: "))
D = float(input("Enter a number for D: "))
E = float(input("Enter a number for E: "))
That code would run fine for python 2.7 I think you are using python 3.5+ so you have to cast the variable so this would become like this
import cmath
A = int(input("Enter a number for A: "))
B = int(input("Enter a number for B: "))
C = int(input("Enter a number for C: "))
D = int(input("Enter a number for D: "))
E = int(input("Enter a number for E: "))
answer = ((((A*10**A)**2)**(B*C))*D**E)
print(answer)
I tested it
Enter a number for A: 2
Enter a number for B: 2
Enter a number for C: 2
Enter a number for D: 2
Enter a number for E: 2
10240000000000000000
there are three ways to fix it, either
A = int(input("Enter a number for A: "))
B = int(input("Enter a number for B: "))
C = int(input("Enter a number for C: "))
D = int(input("Enter a number for D: "))
E = int(input("Enter a number for E: "))
which limits you to integers (whole numbers)
or:
A = float(input("Enter a number for A: "))
B = float(input("Enter a number for B: "))
C = float(input("Enter a number for C: "))
D = float(input("Enter a number for D: "))
E = float(input("Enter a number for E: "))
which limits you to float numbers (which have numbers on both sides of the decimal point, which can act a bit weird)
the third way is not as recommended as the other two, as I am not sure if it works in python 3.x but it is
A = num_input("Enter a number for A: ")
B = num_input("Enter a number for B: ")
C = num_input("Enter a number for C: ")
D = num_input("Enter a number for D: ")
E = num_input("Enter a number for E: ")
input() returns a string, you have to convert your inputs to integers (or floats, or decimals...) before you can use them in math equations. I'd suggest creating a separate function to wrap your inputs, e.g.:
def num_input(msg):
# you can also do some basic validation before returning the value
return int(input(msg)) # or float(...), or decimal.Decimal(...) ...
A = num_input("Enter a number for A: ")
B = num_input("Enter a number for B: ")
C = num_input("Enter a number for C: ")
D = num_input("Enter a number for D: ")
E = num_input("Enter a number for E: ")
Related
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(a, "+", b, "=", add(a, b))
I don't know why it doesn't wanna add
You need to convert select into an int
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2"))
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(a, "+", b, "=", add(a, b))
You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string:
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2: "))
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
print(f"{a} + {b} = {add(a, b)}")
Output:
choose 1 to add and 2 to subtract
enter choice 1/2: 1
enter 1st nunber: 21
enter 2nd number: 3
21.0 + 3.0 = 24.0
input returns a string, but in the line if select == 1 you are comparing it to an int. There are several solutions to this, but the solution I would go with is to use only strings, i.e. if select == "1". 1 and 2 are arbitrary values, so it isn't really necessary for them to be converted to numbers. You could just as easily use a and b to accomplish the same goal.
Another useful thing you can do is validate the user input. I would do that with something like this:
while select not in ["1", "2"]:
print(f"you entered {select}, which is not a valid option")
select = input("enter choice 1/2")
This will continue to ask the user to select one of the choices until they enter a valid one, and also has the added bonus of helping you catch errors in your code like the int vs str issue.
As others mentioned, since input returns a str, it should be compared with an object of same type. Just changing 1 to str(1) on line 10 will solve the issue.
def add(a, b):
return a + b
print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == str(1):
print(a, "+", b, "=", add(a, b))
I am writing a python code that returns me the larger of two inputs.
def bigger_num(a, b):
if a < b:
print ("First number is smaller than the second number.")
elif a > b:
print ("First number is greater than the second number.")
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
print(bigger_num(a, b))
Result:
Enter first number: 19
Enter second number : 9
First number is greater than the second number.
None
How do I display the numeric result (a/b) in the print?
Ideal solution example: First number, 19 is greater than the second number
Also, is there a way to remove none from the print result?
You can use the format() method or simply concatenate the number to display it. To remove the None, just call the function without the wrapping it with a print() because you print the output inside the function
def bigger_num(a, b):
if a < b:
print ("First number, {0} is smaller than the second number.".format(a))
elif a > b:
print ("First number, {0} is greater than the second number.".format(a))
else:
print ("Two numbers are equals.")
a = input("Enter first number: ")
a = float(a)
b = input("Enter second number : ")
b = float(b)
bigger_num(a, b)
I want to perform this:
Read two integers from STDIN and print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
Can someone help me on this?
Start slow and break it down
# Get your data from the user, use input
num_one = input("Please enter the first number: ")
num_two = input("Please enter the second number: ")
# Create the sum, diff, and product, casting as integer
sum = int(num_one) + int(num_two)
diff = int(num_one) - int(num_two)
product = int(num_one) * int(num_two)
# Print each output casting as a string since we can't concatenate a string to an integer
print("The sum is: "+str(sum))
print("The difference is: "+str(diff))
print("The product is: "+str(product))
Now you should also do some error checking here incase the user doesn't enter anything:
# Get your data from the user, use input
num_one = input("Please enter the first number: ")
num_two = input("Please enter the second number: ")
if(num_one == "" or num_two == ""):
print("You did not enter enter two numbers. Exiting...")
exit
else:
# Create the sum, diff, and product, casting as integer
sum = int(num_one) + int(num_two)
diff = int(num_one) - int(num_two)
product = int(num_one) * int(num_two)
# Print each output casting as a string since we can't concatenate a
string to an integer
print("The sum is: "+str(sum))
print("The difference is: "+str(diff))
print("The product is: "+str(product))
Python 2.7
raw_input to read the input, int to convert string to integer, print to print the output
a = int(raw_input("numebr 1: "))
b = int(raw_input("numebr 2: "))
print a + b
print a - b
print a * b
Python 3.7
input to read the input, int to convert string to integer, print to print the output
a = int(input("numebr 1: "))
b = int(input("numebr 2: "))
print (a + b)
print (a - b)
print (a * b)
a = int(input())
b = int(input())
from operator import add, sub, mul
operators = [add, sub, mul]
for operator in operators:
print(operator(a, b))
I'm just starting to learn Python from a book. But I keep running into the same problem when I run my script, it says:
File "C:/Users/bob/Desktop/Python/Part3 A.py", line 8, in <module> print(' the average is: ', avg())
File "C:/Users/Bob/Desktop/Python/Part3 A.py", line 6, in avg average = a + b + c / 3
TypeError: unsupported operand type(s) for /: 'str' and 'int'
Did I install "Pycharm" wrong?
Here is my code
def avg():
a = input('please enter a: ')
b = input('please enter b: ')
c = input('please enter c: ')
average = a + b + c / 3
print(' the average is: ', avg())
Did I install "Pycharm" wrong? NO
in python 3 input returns a string
a = int(input("please enter a:")) #this will make the input an integer
# warning if the user enters invalid input it will raise an error
should work fine
you should also change your print line to
print(' the average is: ', avgerage)
you also need to pay attention to order of operations when you calculate the average
average = (a + b + c) / 3
is what you want
you also have indentation problems but im pretty sure thats cause you copied and pasted wrong ... otherwise you would have a different error
def avg():
a = intinput('please enter a: ')
b = input('please enter b: ')
c = input('please enter c: ')
average = a + b + c / 3
print(' the average is: ', avg())
try this instead
def avg():
a = input('please enter a: ')
b = input('please enter b: ')
c = input('please enter c: ')
average = int(a) + int(b) + int(c) / 3
print(' the average is: ', avg())
return;
P.S: Python is indent sensitive
You've got many errors, which are as follows:
def avg():
a = int(input('Please enter a: '))
b = int(input('Please enter b: '))
c = int(input('Please enter c: '))
average = (a + b + c) / 3
print('The average is:', average)
avg() # call function outside
Indent 4 spaces under the scope of the function.
Cast the string input to integers with built-in int.
Use parenthesis, otherwise math is wrong by PEMDAS.
Lastly, print the average, don't call function recursively.
You are trying to divide a string by an integer.
You need to convert your inputs to integers.
def avg():
a = int(input('please enter a: '))
b = int(input('please enter b: '))
c = int(input('please enter c: '))
average = (a + b + c) / 3
return average
print(' the average is: ', avg())
You are applying arithmetic operations on string input. Convert it to int before using
int(input('please enter a: '))
I'm trying to write a program that asks the user for 4 integers and prints the largest odd number that was entered. Here is the code:
a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")
numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
if i%2!=0:
odd_numbers.append(i)
else:
print "This is not an odd number."
for nums in odd_numbers:
max_num = max(odd_numbers)
print max_num
And here is the error that I'm receiving:
line 10, in <module>
if i%2!=0:
TypeError: not all arguments converted during string formatting
What am I doing wrong ?
raw_input() returns a string. As a result, numbers list becomes a list of strings. % operation behavior depends on the variable type, in case of string it is a string formatting operation:
>>> s = "3"
>>> s % 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
In case of int, it gives you a division remainder:
>>> n = 3
>>> n % 2
1
You need to convert all the inputs to int:
a = int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))
To avoid having a redundant code, you can simplify filling the numbers list using list comprehension:
numbers = [int(raw_input("Enter an int: ")) for _ in xrange(4)]
Because You are input is string convert it into int
>>> a =raw_input("Enter an int: ")
Enter an int: 10
>>> type(a)
<type 'str'>
Try This :
a =int(raw_input("Enter an int: "))
b = int(raw_input("Enter an int: "))
c = int(raw_input("Enter an int: "))
d = int(raw_input("Enter an int: "))
OR
for i in numbers:
if int(i)%2!=0:
odd_numbers.append(i)
Your Output Should be look like this :
>>>
Enter an int: 10
Enter an int: 20
Enter an int: 20
Enter an int: 50
[10, 20, 20, 50]
This is not an odd number.
This is not an odd number.
This is not an odd number.
This is not an odd number.
raw_input will return you a string. So, each element in numbers are string like
numbers = ["1", "2", "3", "4"]
When you try i%2, python evaluates % as the string formatting operator but could not find any place-holder in the string for formatting and raise error. So you must parse your input to int
a = int(raw_input("Enter an int: "))
Or you can use input, which will evaluate your input to proper type (int in your case)
a = input("Enter an int: ")
But using input is not recommended if you are not experienced with it and eval as it states in the docs:
Equivalent to eval(raw_input(prompt)).
This function does not catch user errors. If the input is not syntactically valid, a SyntaxError will be raised. Other exceptions may be raised if there is an error during evaluation.
If the readline module was loaded, then input() will use it to provide elaborate line editing and history features.
Consider using the raw_input() function for general input from users.
You input strings but you need to do calculations with ints.
I you do print type(a) for instance you will see that you actually got a string as input. The way to parse it to an int is to use the built in function int().
a = raw_input("Enter an int: ")
b = raw_input("Enter an int: ")
c = raw_input("Enter an int: ")
d = raw_input("Enter an int: ")
numbers = [a, b, c, d]
odd_numbers = []
print numbers
for i in numbers:
value = int(i)
if value%2!=0:
odd_numbers.append(value)
else:
print "This is not an odd number."
for nums in odd_numbers:
max_num = max(odd_numbers)
print max_num