user5105018
user5105018

Reputation: 25

Check selection and compare to list for python

What I am trying to do is check that an input from the user (using raw_input) is a valid option within a global list. Below is what I have up to this point.

def car():
    print "You have selected the 'car' option.",
    print "Are you sure this is what you want?"
    car_sure = raw_input("Enter Yes or No: ").lower()

    if car_sure == "yes":
        car_brand_choice()

    elif car_sure == "no":
        print "You no longer want a car. Taking you back to select your vehicle type."
        type()

    else:
         dead("Not a valid option. You lose your vehicle purchasing opportunity.")

def car_brand_choice(): 
    print "These are the car brands I can provide to you."
    print "\n".join(car_brands)
    selection = raw_input("Now is your chance to pick which brand you want. ").title()
    print "You selected %s\n" %selection
    print "I have to verify your selection is valid.\n"

    if selection in car_brands:
        print "Valid selection. You may continue."

    else:
        print "Not valid selection."
        print "Go back and select a valid brand.\n"
        car_brand_choice()


start()

The verification will then be used to select a different valid brand or allow the user to proceed with current brand. The code is formatted properly in Notepad++, I hope. I just don't know how to get the proper formatting to show up here. I'm sure there is something similar out there already but I just could not find it.

Upvotes: 2

Views: 210

Answers (2)

Kshitij Saraogi
Kshitij Saraogi

Reputation: 7639

Well, it seems as if you are a beginner.

The thing that you need to solve your problem is in.

selection = raw_input("Now is your chance to pick which brand you want. ")
print "You selected ", selection
if selection in car_brands:
    print "It is in the list"
else:
    print "Its not in the list"

Add this in your car_brand_choice(). For further readings, check the docs

Upvotes: 0

grovesNL
grovesNL

Reputation: 6075

You may simply use the in operator.

>>> 'BMW' in car_brands
True
>>> 'bmw' in car_brands
False

As you can see, it's case sensitive. In your case, you could do something like:

if selection.lower() in car_brands:
    print "Valid car brand."
else
    print "Invalid car brand."

Also, I would remove both instances of '\n' from car_brands. That is not a car brand. You should handle line formatting somewhere else.

Upvotes: 1

Related Questions