Continue while loop after return True - python

I am creating a function which returns True when a number(here X) is Prime.
So I am checking whether the given number is evenly divisible by integers from 2 to X-1.
But the while loop breaks when the check returns True.
Help
def is_prime(x):
n = 2
if x < 2:
return False
elif x == 2:
return True
else:
while True and n < x:
if x % n == 0:
return False
else:
n += 1
return True #--The loop is breaking here--

You code should look like this:
def is_prime(x):
n = 2
if x < 2:
return False
elif x == 2:
return True
else:
while n < x:
if x % n == 0:
return False
else:
n += 1
# Put the return True after the loop
return True
print('{}: {}'.format(10, is_prime(10)))
print('{}: {}'.format(11, is_prime(11)))
print('{}: {}'.format(0, is_prime(0)))
print('{}: {}'.format(1, is_prime(1)))
print('{}: {}'.format(2, is_prime(2)))
print('{}: {}'.format(113, is_prime(113)))
Output:
10: False
11: True
0: False
1: False
2: True
113: True

Well You used return statment in loop, so it exited from method. You need to change the logic of this loop. Check here:
Python Prime number checker

Related

Why does one part of conditional statements in Python returns None while others are ok?

I need to write a code that prints out valid or invalid for an input of letters and numbers for a license plate. The conditions are: first two characters must be letters, characters have to be between 2 and 6, and if numbers are used, 0 should not be the first, nor should a number appear before a letter.
I put the code below on Thonny and cannot understand why len(l) == 4 part of the conditional statement for def valid_order() returns None and does not execute the next line of the code whereas others work fine. My code should return "Valid" for CSAA50, but it returns invalid. Why?
Also, is there an elegant way to write def valid_order()?
def main():
plate = input("Plate: ")
if is_valid(plate):
print("Valid")
else:
print("Invalid")
def is_valid(s):
if s[0:2].isalpha() and 6 >= len(s) >= 2 and s.isalnum() and valid_order(s):
return True
else:
return False
def valid_order(c):
n = []
l = list(c[2:len(c)])
for i in c:
if i.isdigit():
n += i
if n and n[0] == "0":
return False
if len(l) == 2:
if l[0].isdigit() and l[1].isalpha():
return False
if len(l) == 3:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha():
return False
else:
if l[1].isdigit() and l[2].isalpha():
return False
if len(l) == 4:
if l[0].isdigit():
if l[1].isalpha() or l[2].isalpha() or l[3].isalpha():
return False
else:
if l[1].isdigit():
if l[2].isalpha() or l[3].isalpha():
return False
else:
if l[2].isdigit() and l[3].isalpha():
return False
else:
return True
main()

Blank List, Return False

I'm looking to write a function definition named has_evens that takes in sequence of numbers and returns True if there are any even numbers in the sequence and returns False otherwise.
My code is correct, except when it receives something empty, like "([])". I need to account for that. Here's my code:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
elif num % 2 != 0:
return False
if ([]):
return False
The final part is a desperate attempt to account for blank lists. More formally, it needs to pass this assertion:
assert has_evens([]) == False
You should only return True when an even is found:
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
return False
Python has an any function to make this simpler:
def has_evens(s):
return any(num % 2 == 0 for num in s)
I answered my own question. I just needed to un-indent my lines
def has_evens(s):
for num in s:
if num % 2 == 0:
return True
else:
return False

Why is this function with a return value returning none?

Ok, so here is my code:
def is_prime(n):
n = abs(int(n))
if n < 2:
return False
elif n == 2:
return True
elif n%2 == 0:
return False
else:
prime(n)
def prime(n):
for x in range(3, int(n**0.5)+1,2):
if n%x == 0:
return False
else:
return True
print is_prime(6577)
But whenever I run this in my shell it returns 'None', I don't understand why. Any help would be appreciated.
Your final else in is_prime returns nothing. You can even remove the else altogether, but that's just personal preference
def is_prime(n):
# You don't really need to take abs value cause you already do a check for < 2 which includes negative numbers
n = abs(int(n))
if n < 2:
return False
elif n==2:
return True
elif n%2 == 0:
return False
return prime(n)

'For' iterator in python doesn't return the right answer

I wrote this in python to calculate the number of primes under a given value. It prints "0" when I execute the code. Could anyone tell me why my code is going wrong?
def is_prime(x):
if x<2:
return False
else:
for value in range(2, x):
if x%value == 0:
return False
else:
return True
def primes_in(x):
primes = [ ]
for value in range(2, x+1):
if is_prime(value):
primes.append(1)
elif not is_prime(value):
primes.append(0)
else:
primes.append(0)
return sum(primes)
print primes_in(25)
See range function.
range(start, stop[, step])
for value in range(2, x+1):
if x%value == 0:
return False
This means value goes from 2 to x included. Which means that there will necessarily be x%value == 0. So your function always return False and then primes is a list of 0.
You should use for value in range(2, x).
The issue is in your is_prime function , you are looping from 2 to x inclusive of both , so x%x is always 0 ,and hence it will always return False.
You just need to loop till the sqrt of the number.
Example code -
def is_prime(x):
if x<2:
return False
else:
for value in range(2, int(x**(1/2))+1):
if x%value == 0:
return False
else:
return True
Also, in the other function you should start
def is_prime(x):
if x<2:
return False
else:
if x == 2:
return True
for value in range(2, int(x**(0.5)) + 1):
if x%value == 0:
return False
return True
def primes_in(x):
primes = []
for value in range(2, x+1):
if is_prime(value) == True:
primes.append(1)
elif is_prime(value) == False:
primes.append(0)
else:
primes.append(0)
return sum(primes)
print primes_in(25)

Function to check prime according to specfic instructions

I have to create a function according to some specific instructions. It is designed to check if a number is prime or not. I know there are different ways to do this, and I am sorry if this is a stupid question. I am new to programming.
Anyways, here are the instructions (pseudocode):
Function isPrime(n)
if n=1 then return false
else
if n<4 then return true #2 and 3 are prime
else
if n mod 2=0 then return false
else
if n<9 then return true #we have already excluded 4,6 and 8.
else
if n mod 3=0 then return false
else
r=floor( sqrt(n) ) #sqrt(n) rounded to the greatest integer r so that r*r<=n
f=5
while f<=r
if n mod f=0 then return false (and step out of the function)
if n mod(f+2)=0 then return false (and step out of the function)
f=f+6
endwhile
return true (in all other cases)
End Function
and here is my code so far: (Edited for correct indentation)
def isrime(n):
if n == 1:
return False
elif n < 4:
return True
elif n & 2 == 0:
return False
elif n<9:
return True
elif n %3 == 0:
return False
????? (Don't know what to write)
else:
return True
Thanks in advance
def isPrime(n):
if n == 1:
return False
elif n < 4:
return True
elif n % 2 == 0: # needs modulo not &
return False
elif n < 9:
return True
elif n % 3 == 0:
return False
else:
r = n**.5
f = 5
while f <= r:
if n % f== 0:
return False #(and step out of the function)
if n % (f+2)== 0:
return False# (and step out of the function)
f+=6
return True
def is_prime(n):
if n <= 3:
if n <= 1:
return False
return True
if not n%2 or not n%3:
return False
for i in range(5, int(n**0.5) + 1, 6):
if not n%i or not n%(i + 2):
return False
return True

Categories