Julian Ion
Julian Ion

Reputation: 11

(Python 3.5.2) How can I find which item on a list my input is?

How can I find which position on a list an input is, without using 'if' statements? My current code is below. I want to remove the if statements, so that when a breed is inputted, the computer outputs "Great choice!" then separately outputs the price, in as compact code as possible. I need something which finds which value on a list an input is, the prints the corresponding position from ANOTHER list.

dog_breed_list = ["daschund", "chihuahua", "French boxer", "Jack Russell", 
"poodle"]

dog_price_list = [350, 640, 530, 400, 370]

dog_choice = input("Welcome to the Pet Shop. \nWhich is your breed choice?")

if dog_choice == dog_breed_list[0]:
    print("Great choice! This breed costs £350.")
elif dog_choice == dog_breed_list[1]:
    print("Great choice! This breed costs £640.")
elif dog_choice == dog_breed_list[2]: 
    print("Great choice! This breed costs £530.")
elif dog_choice == dog_breed_list[3]:
    print("Great choice! This breed costs £400.")

Upvotes: 1

Views: 95

Answers (2)

Eric Ed Lohmar
Eric Ed Lohmar

Reputation: 1922

If you must uses a list for this, you can use the .index() function.

dog_breed_list = ["daschund", "chihuahua", "French boxer",
                  "Jack Russell", "poodle"]

dog_price_list = [350, 640, 530, 400, 370]

dog_choice = input("Welcome to the Pet Shop. \nWhich is your breed choice?")

try:
    dog_price = dog_price_list[dog_breed_list.index(dog_choice)]
    print("Great choice! This breed costs £{}.".format(dog_price))

except ValueError:
    print('That dog is not found in the list.')

The try-except block is because .index() throws a value error if it doesn't find what it's looking for in that list.

Upvotes: 1

Michael H.
Michael H.

Reputation: 3483

Using a dictionary:

dog_breed_list = ["daschund", "chihuahua", "French boxer",
                  "Jack Russell", "poodle"]

dog_price_list = [350, 640, 530, 400, 370]

dictionary = {dog_breed_list[n]: dog_price_list[n]
              for n in range(len(dog_breed_list))}

dog_choice = input("Welcome to the Pet Shop. \nWhich is your breed choice? ")

if dog_choice in dictionary:
    print("Great choice! This breed costs £"+str(dictionary[dog_choice])+".")

Upvotes: 3

Related Questions