1

I am brand new to python and am struggling with while loops and how inputs dictate what's executed. Here is what I am looking for: If the user inputs an invalid country Id like them to be prompted to try again. If they enter a valid country Id like the code to execute. lastly if they type 'end' when prompted to enter a country id like the program to end. Here is what I have so far:

while True:
    my_country = input('Enter a valid country: ')
    if my_country in unique_countries:
        print('Thanks, one moment while we fetch the data')

Some code here

  #Exit Program
    else:
        my_country == "end"
        break 

The problems I am running into is that, as currently written, if I enter an invalid country it ends the program instead of prompting me again. Thank you in advance. I am also new to stack overflow, sorry for the horrible formating.

1
  • did you look to see if this question has already been asked and answered on here? That could help solve your problem faster than posting and waiting for someone to respond. Commented May 15, 2020 at 22:40

5 Answers 5

2

You need an elif in there. Try this:

while True:
    my_country = input('Enter a valid country: ')
    if my_country in unique_countries:
        print('Thanks, one moment while we fetch the data')
        # Some code here
        #Exit Program
    elif my_country == "end":
        break
    else:
        print ("Try again.") 

edited

Sign up to request clarification or add additional context in comments.

Comments

1

The way around this is to add:

if my_country not in unique_countries:
   continue

just before your first if statement. Hope this helps!

Comments

1

Make your while loop to False. Follow the below code:

unique_countries = ['India', 'USA', 'Canada', 'Japan']

valid = True
while valid:
    my_country = input('Enter a valid country: ')
    if my_country in unique_countries:
        print('Thanks, one moment while we fetch the data')
        # Some code here
        valid = False # This will Exit Program
    elif my_country == "end":
        valid = False
    else:
        print("Country Name entered is not valid...")

Comments

0

here you go:

while True:
    my_country = raw_input('Enter a valid country:')
    if my_country in unique_countries:
        print('Thanks, one moment while we fetch the data')
        break
    elif  my_country == "end":
        break
    else:
        continue

Comments

0

You can just edit your code from

else:
        my_country == "end"
        break 

to -

elif my_country == "end":
    break 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.