Skip to content
Advertisement

How to accept input from an enumerated list in Python?

So I have a list that I want to number using enumerate(), then have the user choose an item from the list using the corresponding number. Is there a way to do this?

(This is broken code but hopefully, you get an idea of what I want to do)

print("Which house do you want to sell")
for number,address in enumerate(market['addresses'], 1):
    print(number, '->', address)
userSell = input("> ")
if userSell in enumerate(market['addresses']):
    print(f"Sold {address}")
else:
    print("Address not found...")

Advertisement

Answer

It’s always a good idea to validate user input – especially when you’re expecting numeric values.

If you do that in this case there’s no need to lookup the address after user input because you will already have validated it.

market = {'addresses': ['1 Main Road', '2 Long Street', '100 Pall Mall']}
addresses = market['addresses']
print("Which house do you want to sell?")
for number, address in enumerate(addresses, 1):
    print(number, '->', address)
while True:
    try:
        userSell = int(input("> "))
        if 0 < userSell <= len(addresses):
            break
        raise ValueError('Selection out of range')
    except ValueError as ve:
        print(ve)
print(f'Sold {addresses[userSell-1]}')

Output:

Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 2
Sold 2 Long Street

With invalid user input:

Which house do you want to sell?
1 -> 1 Main Road
2 -> 2 Long Street
3 -> 100 Pall Mall
> 0
Selection out of range
> 4
Selection out of range
> foo
invalid literal for int() with base 10: 'foo'
> 1
Sold 1 Main Road
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement