I need a bit of help in finishing this code. I am stuck trying to figure out what's wrong with my code. I don't know how to loop back from the top using while loop. It also wont print the last bit. I got the prime numbers settled but I don't know how the looping back works. May you help me?
while True:
num=int(input("Enter a number:"))
no="n"
yes="y"
if num >=1:
for i in range(2, num):
if (num % i) == 0:
print(num,"is not a prime number")
break
else:
print(num,"is a prime number")
x=str(input("If you want to continue press y, n if not:"))
if x==yes:
print()
#this part I don't know how to loop back to the start
elif x==no:
print("Okay")
#and also the loop won't stop and print the text up there^^^ when I choose n
put the if in the while loop only, and break out of the while loop if no
while True:
...
x=str(input("If you want to continue press y, n if not:"))
if x=="no":
print("Okay")
break
If you want this to repeat infinitely, your code structure might look like this:
while True: # The outer while loop, only ends when the player says "n"
while True:
# This is where you get the prime nums, paste the code for that here
if x == "n":
break # This method will only stop the loop if the input is "no", else it keeps looping forever
Or, more simply, you can do this in just one loop. The structure would be like this:
while True:
# Get if the num is prime, paste the code for that
if x == "n":
break
Possible solution if the following:
def is_prime(num):
if num <= 1:
return False
if num % 2 == 0:
return num == 2
d = 3
while d * d <= num and num % d != 0:
d += 2
return d * d > num
while True:
num=int(input("Enter a number: "))
if is_prime(num):
print(f'{num} is a prime number')
else:
print(f'{num} is not a prime number')
x = str(input("If you want to continue enter Y, or N if not: ")).lower()
if x == 'y':
print("let's start over...\n")
elif x == 'n':
print("Okay, see you")
break
Returns:
You can use code like this. In my opinion function more usefull for check prime numbers.
def is_prime(x):
for d in range(2, int(x**0.5)+1):
if x % d == 0:
return False
return x > 1
no, yes = "n", "y"
x = yes
while x == yes:
num=int(input("Enter a number:"))
if is_prime(num):
print(num,"is a prime number")
else:
print(num,"is not a prime number")
x = input("If you want to continue press y, n if not:")
print("Okay")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.