Home > Software design >  How to loop back to the beginning in Python
How to loop back to the beginning in Python

Time:04-07

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

  
            

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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:

![enter image description here

  • Related