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: '))
Related
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))
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: ")
This is my code. I am doing a beginer execise. When I run the program
I can put the values, but when I go out of the loop the following error message appears:
a + = float (input ("Enter the product cost"))
ValueError: could not convert string to float:
Can someone help me?
Here it goes:
e = 0.25
f = 0.18
a = 0.0
while True:
a += float(input("Enter the product cost: "))
if a == "":
break
b = a*e
c = a*f
d = a+b+c
print ("tax: " + b)
print ("tips: " + c)
print ( "Total: " + d)
You are combining two operations on the same line: the input of a string, and the conversion of the string to a float. If you enter the empty string to end the program, the conversion to float fails with the error message you see; the error contains the string it tried to convert, and it is empty.
Split it into multiple lines:
while True:
inp = input("Enter the product cost: ")
if inp == "":
break
a += float(inp)
There are a couple of issues:
the check for a being an empty string ("") comes after the attempt to add it to the float value a. You should handle this with an exception to make sure that the input is numerical.
If someone doesn't enter an empty or invalid string, ever, then you get stuck in an infinite loop and nothing prints. That's because the indentation of your b, c, d calculations and the prints is outside of the scope of the while loop.
This should do what you want:
e = 0.25
f = 0.18
a = 0.0
while True:
try:
input_number = float(input("Enter the product cost: "))
except ValueError:
print ("Input is not a valid number")
break
a += input_number
b = a*e
c = a*f
d = a+b+c
print ("tax: ", b)
print ("tips: ", c)
print ( "Total: ", d)
there are many people who have asked this question but i am a noob at computer programming and cant understand the complicated stuff so i need the answer somewhat dumb down i keep getting the same error and cant correct it
def main():
#A Basic For loop
print('I will display the numbers 1 through 5.')
for num in (1, 2, 3, 4, 5):
print (num)
#The Second Counter code
print('I will display the seconds 1 through 61.')
for seconds in range (1, 61):
print (seconds)
#The Accumulator code
total = 0
for counter in range (5):
number = input (' Enter a number: ')
total = total + number
print (number)
print (total)
here is the full error code :
Traceback (most recent call last):
File "C:/Python34/Lab6-3.py", line 23, in <module>
total = total + number
TypeError: unsupported operand type(s) for +: 'int' and 'str'
First of all, you wrote this:
for counter in range (5):
number = input (' Enter a number: ')
total = total + number
You probably meant this:
for counter in range (5):
number = input (' Enter a number: ')
total = total + number
To answer your question, input() returns a string (like "52"), so you need to convert it to an int (like 52). Fortunately, that's easy in Python:
for counter in range (5):
number = input (' Enter a number: ')
total = total + int(number)
Also, as PEP 8 says, you shouldn't put spaces before function parentheses. You should write this instead:
for counter in range(5):
number = input(' Enter a number: ')
total = total + int(number)
You are trying to add an integer(total) and string(number) at total = total + number. You need to convert var number to integer using int() first. Because input (' Enter a number: ') returns a string.
number = int(input (' Enter a number: '))
Also, your loop should looks like this:
for counter in range (5):
number = int(input (' Enter a number: '))
total = total + number
Total total = total + number needs to be inside your loop.
Be careful if the user try to input a string that can be cast to integer, like "ss" for example. I recommend to add a try/catch
for counter in range (5):
try:
number = int(input (' Enter a number: '))
total = total + number
except,ValueError:
print "You entered a non intenger input"
# you can break loop or continue