Why is my function being ignored? - python

In the console, my program prints the first question, and once the input is entered, prints the second one and terminates. It appears to skip the function. Obviously I've done something(s) wrong, any help would be appreciated. That while-loop still feels wrong.
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
return False
print("This number is not prime.")
else:
i = i - 1
return True
print("This number is prime.")
def Main():
n = int(input("What is the number you'd like to check?"))
Prime(n)
answer2 = input("Thank you for using the prime program.")
Main()

Your function returns before printing output, so nothing ever gets to the console. Consider printing before returning:
def Prime(n):
i = n - 1
while i > 0:
if n % i == 0:
print("This number is not prime.") # Here
return False
else:
i = i - 1
print("This number is prime.") # And here
return True

Related

***Time limit exceeded*** error on python program

when i try to print this line:
print(perfect_square(0))
i should get True but instead i get a time limit exceeded error and i dont know how to fix it.
i tried chaging it to an elif statment instead of 2 separate if statements but i still get that error
This is my current code:
def perfect_square(n):
s = 1
while s != n:
if s*s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
def perfect_cube(n):
s = 1
while s != n:
if s*s * s == n:
return True
elif s == 0:
return True
else:
s +=1
return False
Seems quite clear to me why the perfect_square(0) and perfect_cube(0) cases cause an infinite loop. You start s=1 and always increment it s+=1. It will never be equal to n=0 so you get an infinitely running program. Maybe try making checks for invalid values of n?
def perfect_cube(n):
if n < 1: return False
# ...

Why is my Python prime number checker not working?

Why is my code below giving me wrong results? When I give it numbers like 2 and 3, it says they're not prime numbers. Only some numbers work but for the most part it gives wrong answers.
def prompt_input(input_msg, error_msg):
while True:
userinput = input(input_msg)
try:
integer = int(userinput)
if integer > 1:
return integer
print(error_msg)
except ValueError:
print(error_msg)
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
primenum = prompt_input(
"Give an integer that's bigger than 1: ",
"You had one job"
)
if check_prime(primenum):
print("This is a prime.")
else:
print("This is not a prime.")
First issue: Your for loop returns after one iteration, so the correct return logic would be:
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True
However you are implementing this incorrectly as well, the loop needs to iterate up to the sqrt of the number.
def check_prime(number):
for i in range(2, int(sqrt(number))+1):
if number % i == 0:
return False
return True
Hope this helps!
Need to unindent the return True.
def check_prime(number):
for i in range(2, number):
if number % i == 0:
return False
return True

'None' is printed when I want 'True' for input 5

In this primality test program, 'None' is printed when I input a prime, instead of 'True'. How can I get it to print 'True'?.
def main():
import math
def check_n(n):
n_s = int(math.sqrt(n))
for i in range(2, n_s):
if (n_s % i) == 0:
return False
break
else:
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
main()
You need to change int(math.sqrt(n)) to int(math.sqrt(n)+1), because range runs until n_s-1. So if the input is 5, range(2,int(math.sqrt(5))) is just range(2,2), which is empty.
In addition, you need to take the return True outside of the for loop, otherwise your code may stop in a too early stage. You also don't need the break statement after return False (the function will never arrive to that line, as it will return False if it enters to that if statement).
Finally, change if (n_s % i) == 0: to if (n % i) == 0:, as you need to check if n is divisible by i (and not its square root).
Here is a more clean version:
import math
def check_n(n):
n_s = int(math.sqrt(n)+1)
for i in range(2, n_s):
if (n % i) == 0:
return False
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
First: Your break statement is redundant.
Second: For values such as 3 the for loop is never executing because value
n_s is less than 2 and since the for loop isn't executing the
python is returning the default value None(which is returned when
no value is specified).
Hence your check_n(n) function has to be
def check_n(n):
n_s = int(math.sqrt(n))
for i in range(2, n_s + 1):
if (n_s % i) == 0:
return False
return True
one liner :
check_n = lambda n : sum([i for i in range(2, int(math.sqrt(n)+1)) if n % i == 0]) == 0
don't overcomplicate things ..
Your range is (2,2) or None when you choose anything less than 9.
So to solve your first problem: add 2 to n_s (for input 3)
You also have a problem with your logic.
Your for loop should be checking that n mod i is 0, not n_s.
This should work:
def main():
import math
def check_n(n):
n_s = int(math.sqrt(n)+1)
for i in range(2, n_s):
if (n % i) == 0:
return False
return True
def msg():
n = int(input('Enter a number, I will return True if it is a prime'))
return n
print(check_n(msg()))
main()

Do while loops have local variables in Python?

I am trying to use a while statement like so:
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
However, when I try to use variable n later, it gives me the "local variable 'n' referenced before assignment' UnboundLocalError. That means that n cannot be recognized as a variable in the def I am using, because it only exists in the while statement? Is this possible?
The whole code:
import time
from sys import argv
import os
os.system("cls")
print "Welcome to Number counter 2.0!"
a = True
def program():
global a
if a == False:
os.system("cls")
o = 0
while o == 0:
try:
n = int(raw_input("Which number do you want to begin with?"))
o = 1
except:
o = 0
print "Please use a valid number."
if n == "/historyKeep false":
if a == False:
print "Command historyKeep is already set to false."
else:
a = False
print "Command set successfully."
elif n == "/historyKeep true":
if a == True:
print "Command historyKeep is already set to true."
else:
a = True
print "Command set successfully."
if n == "/historyKeep false":
n = raw_input("Which number do you want to begin with?")
elif n == "/historyKeep true":
n = raw_input("Which number do you want to begin with?")
d = raw_input("How many seconds between each number?")
d = int(d)
total_s = n * d
while n > 0:
print n
time.sleep(d)
n = n - 1
print "Done in", total_s, "seconds in total!"
end_q = raw_input("Exit or retry? (e/r)")
if end_q == "e":
os.system("cls")
print "Exiting."
time.sleep(0.5)
os.system("cls")
print "Exiting.."
time.sleep(0.5)
os.system("cls")
print "Exiting..."
time.sleep(0.5)
os.system("cls")
exit(0)
elif end_q == "r":
program()
program()
You set a = True at the beginning. You then test if a == False and only set n if it is. But then you test n == "/history.... n has not been set at this point.
You need to make sure n is assigned before you use it. It is not enough to just mention it in a branch that is not taken.
n is not defined in the scope that you are trying to use it to fix this define it outside of the while loop and the if statement the while loop is in:
global a
n = 0
Then when you ask the user for what number to start with, that value will replace 0, and you should be good to go. Also instead of declaring global a, why not just make a an input argument for the program() function?
Just to make sure, declare n outside of the loop first:
n = None
while True:
try:
n = int(raw_input("Text..."))
break
except:
print("Please enter a valid number!")
Note: Usually, you would use break to exit a loop. This is because your method requires an extra variable, which uses more memory (not much, but if you keep doing it, it will stack up).

Python issues with return statement

Hello I'm very new to python and was wondering if you could help me with something.
I've been playing around with this code and can't seem to get it to work.
import math
def main():
if isPrime(2,7):
print("Yes")
else:
print("No")
def isPrime(i,n):
if ((n % i == 0) and (i <= math.sqrt(n))):
return False
if (i >= math.sqrt(n)):
print ("is Prime: ",n)
return True
else:
isPrime(i+1,n)
main()
Now the output for the isPrime method is as follows:
is Prime: 7
No
I'm sure the function should return true then it should print "Yes".
Am I missing something?
You are discarding the return value for the recursive call:
def isPrime(i,n):
if ((n % i == 0) and (i <= math.sqrt(n))):
return False
if (i >= math.sqrt(n)):
print ("is Prime: ",n)
return True
else:
# No return here
isPrime(i+1,n)
You want to propagate the value of the recursive call too, include a return statement:
else:
return isPrime(i+1,n)
Now your code prints:
>>> isPrime(2,7)
is Prime: 7
True

Categories

Resources