How do I divide a number stored inside a variable? [duplicate] - python

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

Related

Python Calculator with lists and loops [duplicate]

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.

unsupported operand type(s) for /: 'str' issue [duplicate]

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

Python Prime number checker not working

I'm trying to build a simple Prime Number checker in Python 3.x and I'm running into some issues. I will post my code and then explain my difficulties.
number = input("Please enter a number: ")
is_prime = True;
for factor in range(2, number):
if number % factor == 0:
is_prime = False;
if is_prime == True:
print("%d is a prime number!") % number
else:
print ("%d is NOT a prime number!") % number
Now when I run the following code, I get this error:
C:\Users\clark\Documents\Python Projects>python PrimeNumberChecker.py
Please enter a number: 4 Traceback (most recent call last): File
"PrimeNumberChecker.py", line 5, in
for factor in range(2, number): TypeError: 'str' object cannot be interpreted as an integer
Now, from my limited understanding of Python the input method that I'm using to evaluate the number variable should return an integer so I'm not sure why it's telling me there's a conversion issue. Could anybody shed some light on what's going on here? I'm very new to Python.
Thanks
In Python 3.x, you need to convert your variable number to int like this:
number = int(input("Please enter a number: "))
See these two examples from the two version of Python that I have on my machine:
In Python 3.4:
>>> number = input("Please enter a number: ")
Please enter a number: 4
>>> type(number)
<class 'str'>
In Python 2.7:
>>> number = input("Please enter a number: ")
Please enter a number: 4
>>> type(number)
<type 'int'>
Please take a look at this important answer of How can I read inputs as integers in Python?
In python2.x
number = input("Please enter a number: ")
number will be a int. But in python3.x it will be str. You are using python.3x so you have to convert that into integer. with using int.
number = int(number)
Might be you are referenced a code which is wrote in python2.x
You could try this one
number=int(input("please enter a number")
counter=0
for factor in range (1,number):
if number%factor==0:
counter=counter+1
if counter==2:
print(number,"is prime")
else:
print(number,"is not prime")

Input to list and operate on it

I've just started with Python (3.x), and while it is fairly easy to pick up, I'm trying to learn how to work with lists.
I've written a small program which asks for the amount of numbers to input, then asks for the numbers. Where I'm scratching my head a little is here;
t += numList[int(i)]
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
I'm sure it's obvious to someone else. I thought that lists used an integer index? And that referencing that index would return the contents?
(I have a C++ background, so I'm finding that some things don't work how I thought they would).
Full program here;
runLoop = True
numList = []
def avg():
t = 0
i = 0
while i < len(numList):
t += numList[i]
i += 1
print (" total is " + str(t))
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for"))
while len(numList) < maxLen:
numList.append(input("Enter number : "))
avg()
if input("Would you like to run again? (y/n) ") == "n":
quit()
Type casting:
Type casting is missing in following statement
numList.append(input("Enter number : "))
e.g. Use input() method for python 3.x
>>> a = raw_input("Enter number:")
Enter number:2
>>> type(a)
<type 'str'>
>>> b = int(a)
>>> type(b)
<type 'int'>
>>>
Add Integer type variable with Integer type variable: This will raise exception at t += numList[i] statement because we are adding integer variable with string variable, it is not allowed.
e.g.
>>> 1 + "1"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>>
No need to check length of list in while loop while i < len(numList):. We can iterate directly on list.
e.g.
>> numList = [1,4,10]
>>> total = 0
>>> for i in numList:
... total += i
...
>>> print total
15
>>>
Inbuilt sum() function: We can use inbuilt function sum() to get from list.
e.g.
>>> numList = [1,4,10]
>>> sum(numList)
15
>>>
Exception handling: It is good programming to handle exception on user input. Use exception handling during type casting. If user enters any non integer number and we are type casting that non integer string into integer that time python interpreter raise ValueError.
e.g.
>>> try:
... a = int(raw_input("Enter Number:"))
... except ValueError:
... print "Wrong number. Enters only digit."
...
Enter Number:e
Wrong number. Enters only digit.
Thanks to Vivik for the answer.
I have now adjusted my simple program and solved the issue I had; code as follows.
runLoop = True
numList = []
def avg(workList):
t = sum(workList)
print ("Average is " + str(t/len(workList)) )
print ("Total is " + str(t) )
while runLoop == True:
maxLen = int(input("Average Calculator : "
"Enter the amount of number "
"to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
avg(numList)
if input("Would you like to run again? (y/n) ") == "n":
quit()
I can see that I could quite easily shorten it down to;
runLoop = True
numList = []
while runLoop == True:
maxLen = int(input("Average Calculator: Enter the amount of number to calculate for : "))
while len(numList) < maxLen:
numList.append(int(input("Enter number : ")))
print ("Average is " + str(sum(numList)/len(numList)) )
print ("Total is " + str(sum(numList)) )
if input("Would you like to run again? (y/n) ") == "n":
quit()
But, the point of my little !/pointless exercise was to explore the relationships of lists, input to lists, and printing lists.
Cheers!

I dont understand this syntax error

I think I'm calculating the conversion from an integer to a binary number wrong. I entered the integer 6 and got back the binary number 0, which is definitely wrong. Can you guys help out? Here's the new code.
def ConvertNtoBinary(n):
binaryStr = ''
if n < 0:
print('Value is a negative integer')
if n == 0:
print('Binary value of 0 is 0')
else:
if n > 0:
binaryStr = str(n % 2) + binaryStr
n = n > 1
return binaryStr
def main():
n = int(input('Enter a positive integer please: '))
binaryNumber = ConvertNtoBinary(n)
print('n converted to a binary number is: ',binaryNumber)
main()
You forgot to call raw_input(). Right now you try to convert your prompt message to an integer which cannot work.
n = int(raw_input('Enter a positive integer please: '))
Of course a try..except around that line would be a good idea:
try:
n = int(raw_input('Enter a positive integer please: '))
except ValueError:
n = 0 # you could also exit instead of using a default value
In n = int('Enter a positive integer please: '), you are trying to make an int out of the string 'Enter a positive...'. I would assume you forgot your raw_input(). You could either do
n = int(raw_input('Enter a positive integer please: '))
or
n = raw_input('Enter a positive integer please: ')
n = int(n)
You can't cast a arbitratry string literal to an int. I think what you mean to do is call a prompt method of some sort that takes input from the user.

Categories

Resources