Python – a function that determines the first n prime numbers
Question:
IM VERY NEW TO PYTHON, THANKS FOR UNDERSTANDING
Write a function that determines the first n prime numbers. The value of n is taken from a user input.
The program should print all the prime numbers requested.
After doing this task, the program should ask the user again if they would like to print another set of
prime numbers. If yes, the program should redo the task. Otherwise, it should terminate the program.
Use iterations/loops in solving this problem.
Example:
Enter the value of n: 5
The first 5 prime numbers are...
2
3
5
7
11
--End--
Would you like to go again? (Yes/No): Yes
Enter the value of n: 3
The first 3 prime numbers are...
2
3
5
--End--
Would you like to go again? (Yes/No): No
Closing program...
IM VERY NEW TO PYTHON, THANKS FOR UNDERSTANDING
Here is my code:
def prime_list():
n = int(input("Enter the value of n: "))
print("The first", n, "prime numbers are...")
var = 0
num = 2
while True:
prime = True
for i in range (2, num//2 +1):
if num%i == 0:
prime = False
break
if prime == True:
print(num)
var += 1
if var == n:
break
num += 1
print("==END==")
def redo():
text = str(input("Would you like to go again? (Y/N): "))
if text == str("N"):
print("Terminating Program...")
quit()
if text == str("Y"):
prime_list()
prime_list()
redo()
Why does my code run twice only? When executed it only runs twice. How, and why?
Answers:
Found the answer to my question;
just put while True
, on the def redo()
function.
IM VERY NEW TO PYTHON, THANKS FOR UNDERSTANDING
Write a function that determines the first n prime numbers. The value of n is taken from a user input.
The program should print all the prime numbers requested.
After doing this task, the program should ask the user again if they would like to print another set of
prime numbers. If yes, the program should redo the task. Otherwise, it should terminate the program.
Use iterations/loops in solving this problem.
Example:
Enter the value of n: 5
The first 5 prime numbers are...
2
3
5
7
11
--End--
Would you like to go again? (Yes/No): Yes
Enter the value of n: 3
The first 3 prime numbers are...
2
3
5
--End--
Would you like to go again? (Yes/No): No
Closing program...
IM VERY NEW TO PYTHON, THANKS FOR UNDERSTANDING
Here is my code:
def prime_list():
n = int(input("Enter the value of n: "))
print("The first", n, "prime numbers are...")
var = 0
num = 2
while True:
prime = True
for i in range (2, num//2 +1):
if num%i == 0:
prime = False
break
if prime == True:
print(num)
var += 1
if var == n:
break
num += 1
print("==END==")
def redo():
text = str(input("Would you like to go again? (Y/N): "))
if text == str("N"):
print("Terminating Program...")
quit()
if text == str("Y"):
prime_list()
prime_list()
redo()
Why does my code run twice only? When executed it only runs twice. How, and why?
Found the answer to my question;
just put while True
, on the def redo()
function.