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")
Related
I'm really new to python and I'm trying to make an if else statement that can only take integers. I'm trying to make something like this:
num = (input("Enter a number:"))
if (num is an int):
num = num*2
elif (num is a str):
print("please enter a number")
By default input() takes argument as str.
To convert it into int you can do
num1 = int(input("Enter a number:"))
If it is not number above code will throw an error.
ValueError: invalid literal for int() with base 10: 'abc'
To overcome this you can use try-except (Exception handling)
try:
num1 = int(input("Enter a number:"))
num1 = num1*2
except:
print("please enter a number")
You need to do this.
isinstance(<var>, int)
unless you are in Python 2.x in which case you want:
isinstance(<var>, (int, long))
Also, keep in mind that your code will always recive a string because the input function recives the keyboard input as a string.
Decimal to binary in Python
I did this code and I am getting a zero(0) at the end of the answer I don't want that zero
num=int(input("Enter a number:"))
a=0
a=str(a)
while num>0:
a=a+str(num%2)
num=int(num/2)
print(a[::-1],end='')
My Output :
Enter a number:42
1010100
I don't need the final zero
I need
Enter a number:42
101010
A better formation:
num = int(input("Enter a number: "))
a = ''
while num > 0:
a += str(num % 2)
num //= 2
print(a[::-1])
Enter a number: 42
101010
As a beginner, you should pay attention to your programming habits to make your code more concise and readable.
Set a="" and remove a=str(a) should solve your issue
Rather than initialize a to "0", just initialize it to the empty string:
num=int(input("Enter a number:"))
a=""
while num>0:
a=a+str(num%2)
num=int(num/2)
print(a[::-1],end='')
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
print("Enter the number you want to test")
Num1 = input("Enter your number here:")
if (Num1%1 == '0' and Num1%Num1 == '0'):
print ("This number is prime number")
else:
print("This number is nor prime number")
This is failing with an error of TypeError: not all arguments converted during string formatting. What is the cause and how can I fix it?
input returns a string , you should convert it to int:
Num1 = int(input("Enter your name here:"))
And if parts changed to :
if (Num1%1 == 0 and Num1%Num1 == 0):
However your code logic for realize that a number is prime or not is not correct , you should check that number has a factor or not , you should write a for loop through it's lower numbers and realize that.it's simple but I think it's better for you that write it yourself.
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!