I am trying to make a simple prime number detector base on user input. These code line down here I have input 2 and 5 and 123. Even though they are prime number but the program seems to print "not prime number" for any number you input
I have tried a lot but most of my code even didn't print anything.
def check_Prime(f):
if(f<2):
return False
can=math.sqrt(f)
for x in range(2,can):
if(f%x==0):
return False
else:
return True
if check_Prime is True:
print("prime number")
else:
print("not prime number")
I expect if you input a prime number then it will print("prime number") and if you didn't input prime number it will print the other one
You aren't calling the function. Your line if check_Prime is True: is checking if the function itself is true. Which it always is.
You would need to actually call the function with a value like so:
if check_Prime(3) is True:
However you will then discover that this can throw
TypeError: 'float' object cannot be interpreted as an integer
When math.sqrt() returns a non-integer.
You donĀ“t call the function because you check only if the function is available. Change
if check_Prime is True:
print("prime number")
else:
print("not prime number")
to
if check_Prime(<YourInput>) is True:
print("prime number")
else:
print("not prime number")
and fix your TypeError because range only work with integers. Take a look at here or here to learn how to deal with float in range.
Here is a quick function. It is slow. Should you want a speedy function, try this prime checking in python
def check_Prime(number):
if number <= 1:
return False
if number == 2 or number == 3:
return True
if number % 2 == 0:
return False
limit = int(math.sqrt(number)) + 1
for test in range(3, limit, 2):
if number % test == 0:
return False
return True
if check_Prime(3) is True:
print("prime number")
else:
print("not prime number")
import math
def checkPrime(f):
flag = True
if f >= 2:
limit = int(math.sqrt(f)) + 1
for x in range(2, limit):
if f % x == 0:
flag = False
else:
flag = False
return flag
if checkPrime(100):
print("prime number")
else:
print("not prime number")
Related
I can't figure out how to execute a condition that check if the user inputs are equal before checking if it is a prime number. My goal is to ask a user to input two prime numbers. And in the 2nd while loop, I want to make sure that the 2nd number is not equal to the first number in order to be checked if it is a prime number
value_P=[]
value_Q=[]
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True
while True:
try:
P = int(input("Enter a prime number(P): "))
if is_prime(P):
value_P.append(P)
print("P =", value_P)
break;
else:
print(value_P, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
#2nd while loop
while True:
try:
Q = int(input("Enter a prime number(Q). Not the same as the number you entered above: "))
if is_prime(Q):
value_Q.append(Q)
print("Q =", Q)
break;
else:
print(value_Q, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
You can check if the value of Q is inside the P list using an if statement in the 2nd while loop.
while True:
try:
Q = int(input("Enter a prime number(Q). Not the same as the number you entered above: "))
if is_prime(Q):
#here the code made sure it's prime, next statement checks if the "Q" input was already previously used as the "P" input. If it is, the loop breaks.
if Q in value_P:
break
else:
value_Q.append(Q)
print("Q =", Q)
break;
else:
print(value_Q, "is not a prime number")
except ValueError:
print("Provide an integer value...")
continue
Below is my code. I am trying to loop this while code input, so if someone gives anything other than a numeric then it has to respond with the below message and then ask for the number again. But i am stuck it tried many variations of whiel try blocks.. but the output seem to be if the number is valid, then it gives the response[ prime or not] along with the secondary print value about the non numeric and if the input is non numeric, it gives an error for it being non numeric.... any help or suggestions pls
def prime_checker(number) :
is_prime = True
for i in range(2, number) :
if number % i == 0 :
is_prime = False
if is_prime :
print("It's a prime number")
else :
print("Its not a prime number")
should_continue = True
num = int(input("Check this number: "))
prime_checker(number=num)
while not num == int():
result = input("You have entered a non numeric value, please enter a number to continue else enter 'no' to exit. '.\n")
if result == "no":
should_continue = False
print("Goodbye")
You should check for the type of the variable and not the variable itself:
...
while not isinstance(num, int):
....
You cannot have while not num == int() You can have while num.isdigit() == False. Remember when you are using input you are receiving a string. And you need a try: except: block to handle the int(num) check or use num.isdigit(). You are not using your should_continue variable anywhere meaningful. You need to use a break command to exit the while loop.
Changed your code to make it more sensible
I am trying to write a short python script that gives the user a prime number starting with 3 and continues providing the next prime number if the user wishes to see it.
Here is the function I have created. When I run it I cannot move past the number 3 which is where it starts by design. I get the print statement "3 is not a prime number" and then the input() field pops up to which I enter 'Yes' and I expect the variable 'count' to be incremented to 4 and the script to check again if it is prime.
It should go through this process checking every number and returning just the primes, then asking the user if they wish to see another one. Any ideas why I am stuck on and endless loop of "3 is not a prime number"
def prime_number():
game_on = True
while True:
count = 3
for num in range(2,count):
if count % num == 0:
print(f'{count} is not a prime number')
break
elif count % num != 0:
print(f'{count} is a prime number')
break
else:
pass
question = input("Would you like to see another prime number?? Please enter Yes or No: ")
if question == "Yes":
count += 1
else:
break
game_on = False
You should put the starting count value outside of the main loop.
count = 3
while True:
for num in range(2,count):
def prime_number():
game_on = True
count = 3
while True:
for num in range(2, count):
if (count % num) == 0:
print(count,"is not a prime number")
break
else:
print(count,"is a prime number")
question = input("Would you like to see another prime number?? Please enter Yes or No: ")
if question == "Yes":
count = count + 1
continue
return
This solution works well. You could in fact used int(count/2) since no number has a factor greater than itself divided by 2.
Create a function that checks whether a number is a prime number
1 def is_prime(num):
2 for i in range(2,num):
3 if num%i != 0:
4 return False
5 return True
You put the "count = 3" line inside the for loop, so count will just equal 3 for every iteration. The solution would be to declare count before the While loop
game_on = True
count = 3
while True:
...
My code is supposed to take a user's input for a value of 'n' that must be a positive integer, and if it's not positive or if it's a string rather than a integer than it should repeat the input process. Here's my code:
def input_n():
"""obtains n value from user"""
while True:
print("Input number of terms n (must be > 0):")
n = input("> ")
if not n.isdigit():
print("Not a usuable n value")
return None
continue
else:
n = int(n)
if n < 1:
print("Not a usuable n value")
return None
else:
return n
I've tried it with and without the continue statement at the end of the first if loop. It never seems to repeat itself if a negative number or string is inputed. It moves on to the next part of my code (not shown or necessary). Does anyone know why it's not repeating since the while loop remains True?
The return statement ends the function.
So when you execute return None it cannot repeat itself in the cycle since it's already out of it.
You probably want to use continue instead of return None
Looks like you're returning if n isn't a digit, which exits the function.
def input_n():
"""obtains n value from user"""
print("Input number of terms n (must be > 0):")
while True:
n = input("> ")
if not n.isdigit():
print("Not a usable value - must be a number!")
continue
n = int(n)
if n < 1:
print("Not a usable value - too low!")
continue
return n
Try this
def input_n():
print("Input number of terms n (must be > 0):")
while True:
n = raw_input("> ")
if not n.isdigit() or n < 1:
print("Not a usuable n value")
continue
else:
return n
I am trying to return the number if it is an INT and between numbers, an error occurs when you enter a letter . also you have to input the correct value twice to get an input:
def get_number():
b = False
while b == False:
try:
n = (input('Please enter a 6 digit number'))
except ValueError:
continue
if n >= 100000 and n <= 1000000:
b = True
break
return n
if __name__ == '__main__':
get_number()
print get_number()
`
Changed input to raw_input , it now work if someone enters a letter. however when i enter the correct input ,it will keep on looping:
def get_number():
b = False
while b == False:
try:
n = (raw_input('Please enter a 6 digit number'))
except ValueError:
continue
if n >= 100000 and n <= 1000000:
b = True
break
return n
if __name__ == '__main__':
get_number()
print get_number()
There are a few problems with your code.
you could just use input to evaluate whatever the unser entered, but that's dangerous; better use raw_input to get a string and try to cast that string to int explicitly
also, if you are using input, then you'd have to catch NameError and SyntaxError (and maybe some more) instead of ValueError
currently, your if condition would allow a 7-digit number (1000000) to be entered; also, you can simplify the condition using comparison chaining
no need for the boolean variable; just break or return from the loop
you call your function twice, and print only the result of the second call
You could try something like this:
def get_number():
while True:
try:
n = int(raw_input('Please enter a 6 digit number '))
if 100000 <= n < 1000000:
return n
except ValueError:
continue
if __name__ == '__main__':
print get_number()