This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I'm starting out in python and just wrote a simple calculator but it seems to have some errors.Pls help me out
a = raw_input("Enter value of a : ")
b = raw_input("Enter value of b : ")
sum = a + b
sub = a - b
mul = a * b
div = a / b
print"1.Addition"
print"2.Subtraction"
print"3.Multiplication"
print"4.Division"
op = raw_input("Enter the operation to be done : ")
if op == 1:
print"Sum is %d" % sum
elif op == 2:
print"Difference is %d" % sub
elif op == 3:
print"Product is %d" % mul
elif op == 4:
print"Quotient is %d" % div
else:
print"Invalid operation"
Error is
TypeError : Unsupported operand type for -: 'str' and 'str'
You are reading strings, and trying them to subtract them as strings. You have to convert them to numbers first. Just add
a = float(a)
b = float(b)
after the user input
Moreover, sum is a builtin function in python, so you'd better use different names for your variables
change the input into an int by putting int() outside of raw_input.
a = int(raw_input("Enter value: "))
raw_input interprets the user input as strings therefore you need to convert the raw input into an int first before processing them
Related
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
python TypeError not all arguments converted during string formatting [duplicate]
(2 answers)
Closed 11 months ago.
The program should print the entries which are divided into three without the remainder. The problem is "TypeError : not all arguments converted during string formatting python " in the bottom
numbers = [ ]
while True:
inputNumber = (input("Enter a number if you want to terminate this, please tap on 'q' : "))
if inputNumber == "q":
break
numbers.append(inputNumber)
sum = 0
for i in numbers:
sum+=int(i)
print("Sum of the inputs : ", sum)
#unexecutable lines
for i in numbers:
if(i%3 == 0):
print(i)
Variable i is in string format.
Hence type cast it to int before carrying out calculation:
#unexecutable lines
for i in numbers:
if(int(i)%3 == 0):
print(i)
This question already has answers here:
Python Error - TypeError: input expected at most 1 arguments, got 3 [duplicate]
(3 answers)
Closed 1 year ago.
This is the question I was working on. I have created a function to convert binary number to decimal but what I couldn't figure out was how to get values while the number after Enter change
Enter 4 position value
Enter 3 position value
Enter 2 position value
Enter 1 position value
This is the code which I tried but apparently prompt inside input does not work like it does in print function. The numbers after Enter change depending on how much the user wants to enter.
a=int(input("Enter Number of digits : "))
while a<0:
x=int(input("Enter ",a, " position value : "))
input() only expects a single argument; use string formatting to pass it a single string with your position value in it
One of these is likely what you're after (functionally identical, but you may have some preference)
int(input(f"Enter {a} position value: "))
int(input("Enter {} position value: ".format(a)))
Multiple arguments to input() will raise TypeError!
>>> input("foo", "bar")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: input expected at most 1 argument, got 2
You could print before the input
b = 0
a = int(input("Enter Number of digits: "))
# digits = [0 for _ in range(a)]
b |= int(input("Enter MSB Value")) # or digits[a-1] = int(input())
a -= 1
while a > 0:
print("Enter " , a, " position value : ")
x = int(input()) # or digits[a] = int(input())
b |= (x << a) # just an example
a -= 1
But if you want to put the input on the same line, then you need to format or concatenate the string to the input function, which is not what commas do
Regarding the storing of binary numbers, you should ideally be using bit-shift logic (as shown above) for that since you aren't actually entering decimal values, only individual bits. (Logic above not tested for your problem, btw)
And you don't need to write your own function to convert
Python: Binary To Decimal Conversion
This question already has answers here:
for loop in python with decimal number as step [duplicate]
(2 answers)
Closed 1 year ago.
I am trying to create a calculator program that takes user input and stores it in a list and perform the calculation based on their selection. However, I keep running across an error for line 31 saying
TypeError: 'float' object cannot be interpreted as an integer.
Here is the code:
import math
def printIntro():
print("This is a simple calculator.")
print("Select an operation:\n1) Add\n2) Subtract\n3) Divide\n4) Multiply")
while True:
operator = input("Enter your choice of + - / *: \n")
if operator in('+', '-', '/', '*'):
#continue asking for numbers until user ends
#store numbers in an array
list = []
num = float(input("What are your numbers?: "))
for n in range(num):
numbers = float(input("What are your numbers?: "))
list.append(numbers)
if n == '':
break
if operator == '+':
print(add(list))
if operator == '-':
print(subtract(list))
if operator == '/':
print(divide(list))
if operator == '*':
print(multiply(list))
else:
break
Python's range method accepts an integer.
The error is due to the fact that you convert the input to float in num = float(..) before giving it to range(num).
I think in the line where you try to get the number from input causes it:
num = float(input("What are your numbers?: "))
It should work with (I also fixed the prompt message):
num = int(input("How many numbers you have?: "))
for n in range(int(num)): cast num as int inside the for loop such as this. There is a similar comment to this above but here is the fixed code.
This question already has answers here:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
(5 answers)
Closed 2 years ago.
My code:
a = input("Enter a number: ")
b = input("Enter another number: ")
int(a)
int(b)
if a == 0:
print("You cannot divide a number by 0")
if b == 0:
print("You cannot divide by 0")
else:
print("The first number,", a, "divided by the second number,", b, "equals", a / b)
The error:
File "C:/Users/aaron/.PyCharmCE2019.3/config/scratches/scratch_1.py", line 10, in <module>
print("The first number,", a, "divided by the second number,", b, "equals", a / b)
TypeError: unsupported operand type(s) for /: 'str' and 'str'
I have converted it to an integer (obviously not but I think I have!) but wondering where I'm wrong.
By looking at the error what I reckon is that, you are trying to divide two strings.
If the variables a and b are taken as input and not hardcoded try using :
# to take the input
a = int(input())
b = int(input())
If you are hardcoding the values of a and b, avoid the use of single or double quotes.
Using quotes makes the variable a string.
a = '12' # is a string and you can't perform division operation on this
a = 12 # is an integer
You can also convert the string into integer by:
a = int(a) # If initially variable a is a string
print("The first number,", a, "divided by the second number,", b, "equals", a / b)
This should work if both a and b are integers or floats.
int(a)/int(b)
or
a=int(a)
b=int(b)
and str(a) and str(b) in the text
The problem here is that you are trying to divide 2 strings. This is not possible because you can't divide text. You first have to convert them into numbers such as integers or floats.
You tried to do this:
int(a)
int(b)
However, this is not turning the variables from strings to integers because you are not assigning the result of the int() function to the variable.
Basically the int() function is returning a value that is just getting lost.
You can instead do this:
a = int(a)
a = int(b)
If you want you can do it in less lines like this:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
try as 10
print("The first number,", a, "divided by the second number,", b, "equals", int(a) / int(b))
or
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
if you want more to learn give a look at:
Asking the user for input until they give a valid response
This question already has answers here:
TypeError: unsupported operand type(s) for /: 'str' and 'str'
(5 answers)
Closed 6 years ago.
The program I am writing allows you to input any number and the program will identify if the number is a prime number or not. However, I am getting an error as shown below.
I have been having trouble with this line of my code:
chosen = input("Input a number")
number = (chosen) / chosen
When I run it, here is the output:
Input a number1
Traceback (most recent call last):
File "C:\Users\engineer2\Desktop\Programs\prime numbers.py", line 3, in <module>
number = (chosen) / chosen
TypeError: unsupported operand type(s) for /: 'str' and 'str'
Here is the full code:
chosen = input("Input a number")
number = (chosen) / chosen
one = 1
if number == (one):
print ("Its a prime number")
else:
print ("Not a prime")
input ("press enter")
You'd have to try and convert the input into a number, float in this case would be explicit.
Keep in mind you should use raw_input instead of input.
try:
chosen = raw_input("Input a number: ")
number = float(chosen) / float(chosen)
except Exception as e:
print 'Error: ' + str(e)
The issue is that input() returns a string rather than a number.
you first need to convert chosen to a number with chosen = float(chosen). Then mathematical operations should work just fine..
You're trying to divide strings, convert to an int using int().
try:
chosen = int(input("Input a number"))
except ValueError:
print('Not number.')
As a side-note, your algorithm for checking primality is flawed, you need to check every number in the range of your number for no remainder division with n not just the input.
a = int(input("Input a number: ")) # Example -> 7
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
print is_prime(a)
>>> True
# One-liner version.
def is_prime(n):
return all(n % i for i in range(2, n))
print is_prime(a)
>>> True
input() function returns a string instead of an int. Try converting it or using raw_input() instead:
Method 1:
chosen = int(input("Input a number"))
number = (chosen) / chosen
Method 2:
chosen = raw_input("Input a number")
number = (chosen) / chosen