Created
June 15, 2017 01:52
-
-
Save tbelaire/349683370deff9b15caf82dbc56a98f8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## I'm going to start my comments with ## to distiguish them. | |
number = 1 | |
## I'd make this a function which returns True or False | |
## Before you were always returning a list of length 1 or 0, which isn't | |
## that helpful. Remember, just because you name your variable `primes` | |
## here doesn't mean that it affects the variable named `primes` below. | |
def is_prime(number): | |
factors = [] | |
#determine if prime | |
for num in range(1, number+1): | |
#for each whole number less than the input number | |
#divide the input number my it. If the remainder is 0, add to | |
#a list of factors. Else, ignore it. | |
if number % num == 0: | |
factors.append(num) | |
## You can drop the else: pass, it doesn't do anything | |
#If the list of factors is only 1 and the number, add the number | |
#to a list of primes (not working for some reason) | |
## if factors == [1, number]: | |
## primes.append(number) | |
## We can just return the condition directly. | |
return factors == [1, number] | |
## Now I can test this in the terminal interactively | |
## $ python -i primes.py | |
## >>> is_prime(5) | |
## True | |
## >>> is_prime(6) | |
## False | |
## We really don't need this at all, but yes it's correct. | |
def increase_number(number): | |
#increases input number by one (works fine) | |
number = number + 1 | |
return number | |
## To make interactive use easier, I like using this pattern of naming | |
## all my functions, and then just calling the main one. | |
def main(): | |
primes = [] | |
nth_prime = int(input('please type the nth prime you want: ')) | |
print("Trying to find the {}th prime".format(nth_prime)) | |
## I had to define `number` here, since we use it inside the loop | |
## Remember that variables defined in other functions are not visible | |
## here. | |
number = 2 | |
while True: | |
## Now that `is_prime` just returns a boolean, it's easy | |
## to use it in a if. | |
if is_prime(number): | |
print("{} is prime".format(number)) | |
primes.append(number) | |
number = increase_number(number) | |
if len(primes) == nth_prime: | |
print(primes[-1]) | |
break | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment