Thamsen
Thamsen

Reputation: 23

Having trouble getting a while loop to run properly

I am trying to implement the possibility to re-run a loop after after asking the user if they want to do so. Upon saying that the loop shouldn't be run again the loop stops properly. But the loop doesn't start again after the "continue" command.

I have already tried to read some forum posts but I feel a little stuck.

a = "Y"

url = input("Please enter a valid url:")

while (a == "Y"):

    check_url = "https://" in url

        if check_url == False:
            print("Invalid url, please try again.")
            url = input("Please enter a valid url:")
            continue

        else:
            print("url enteret successfully!")
            print("url:",url)

            print("Is the given url correct?")
            a = input("Yes/No:")
            if str(a) == "Y" or str(a) == "y" or str(a) == "YES" or str(a) == "Yes" or str(a) == "yes":
                break
            if str(a) == "N" or str(a) == "n" or str(a) == "No" or str(a) == "NO" or str(a) == "no":
                print("Please try again.")
                continue       
            else:
                print("Invalid entry. Assuming correct url is given.")
                break

Upvotes: 2

Views: 57

Answers (2)

flakes
flakes

Reputation: 23674

Your condition to keep the loop going is "Y", while (a == "Y") but you change the value to "N". Try switching the invariant and starting value.

a = "N"

url = input("Please enter a valid url:")

while (a == "N"):
    ...

Further, you don't really need a value to check against if you exit the loop with the break control statement. Try something like this:

while True:
    url = input("Please enter a valid url:")
    if "https://" not in url:
        print("Invalid url, please try again.")
        continue
    print("url entered successfully!")
    print("url:", url)

    print("Is the given url correct?")
    a = input("Yes/No:")
    if str(a) == "Y" or str(a) == "y" or str(a) == "YES" or str(a) == "Yes" or str(a) == "yes":
        break
    elif str(a) == "N" or str(a) == "n" or str(a) == "No" or str(a) == "NO" or str(a) == "no":
        print("Please try again.")
        continue       
    else:
        print("Invalid entry. Assuming correct url is given.")
        break

Upvotes: 2

CFV
CFV

Reputation: 792

Your loop doesn't continue because a is no longer equal to 'Y'. Add a = "Y" before the continue statement and it should work

Upvotes: 0

Related Questions