-1

I am new to Python and have to write this code for a school project.

When the user says "No", meaning they are not US-based, I want the program to exit. When the user doesn't type in anything I would like it to say "please type y or n" and to keep displaying this message until they respond correctly.

while location == "":
    location = input("Are you based in the US? Y/N ") 
    if location.upper().strip() == "Y" or location.upper().strip() == "YES":
        print("Great to know you're based here in the states")

    elif location.upper().strip() == "N" or location.upper().strip() == "NO": #when input is N or No display not eligible
        print("Sorry to be our supplier you must be based in the US!")
        quit() #stops program
    else:
        location = "" #if NZ based variable is not Y or N set NZ based variable to nothing
        print("Type Y or N") #displays to user To type Y or N
trincot
  • 317,000
  • 35
  • 244
  • 286
roobo
  • 5
  • 4
  • Not exactly sure what you're asking. You want to know how to exit? You may use `import sys` and then use `sys.exit()` – Wololo Aug 20 '18 at 07:27
  • im wanting for the code to keep asking if the company is located in the us untill he answers either yes or no and also want the code to end if he answers no – roobo Aug 20 '18 at 07:33
  • Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Matthias Aug 20 '18 at 08:47

1 Answers1

1

The basic idea here is to make an infinite loop, and break it only when you get the input you want. As you will be calling upper and strip every time you compare the input, it suffices to just call them once when you get the input.

import sys

while True:
    location = input("Are you based in the US? Y/N ").upper().strip()

    if location in {"Y", "YES"}:
        print("Great to know you're based here in the states")
        break
    elif location in {"N", "NO"}:
        print("Sorry, to be our supplier you must be based in the US!")
        sys.exit() # no need to `break` here as the program quits
    else:
        print("Type Y or N")
fractals
  • 816
  • 8
  • 23
  • hello thanks for your solution you helped me fix half of the problem which was to end when the user said no, but how do I also make the program tell the user to again type either yes or no when they are just pressing enter or typing some random words, – roobo Aug 20 '18 at 07:44
  • This code accounts for the cases where the user enters something like "abcd." Do you mean you want to check every time the user hits any key, before even hitting Enter? – fractals Aug 20 '18 at 07:57
  • sorry you actually solved my whole problem i just hadn't implemented the code correctly thanks, – roobo Aug 20 '18 at 08:05
  • No problem :D please consider upvoting/accepting the answer if it helped. Thanks! – fractals Aug 20 '18 at 08:08