0

So we ask the user to input a number and match that number in a list:

numbers = [1, 2, 3]
num_words = ['One', 'Two', 'Three']
print('Type a number from 1 -3: ')
user = int(input())
if user in numbers:
  print(f"{user} is the digit you typed " + ???)

Once that is done I'd like to match what the user typed that was found in the numbers list and print out the corresponding index value in the next list.

So the user types in 1 and it checks numbers and if it finds it, it would print: One from the num_words list to the user.

I also tried a dictionary, but couldn't figure out how to show the matching value to the user based on their input and matching to the dict key:

nums = {1: 'One', 2: 'Two', 3: 'Three'}
print ('Type 1, 2, or 3: ')
user = int(input())

if user in nums.keys():
   print(num.values) #Need it to print the nums.value based on the users input at match to nums.keys
else:
   print('Goodbye!')

However, my Google searching isn't finding anything similar to what I'm trying to do. I found topics on here (example: Stackover Flow Tpoic, Stackover Flow topic 2, but it didn't help because as far as I could understand (and current understanding of Python) it didn't 100% match what I was trying to do.

3 Answers3

1

For the first example with lists, use .index() to find the index location of the number in the first list, then use that value to find the item in the second list:

if user in numbers:
    location = numbers.index(user)
    print(num_words[location])

For the second example with a dictionary, just use standard dict lookup:

if user in nums:
    print(nums[user])
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

The syntax to get the value from a dictionary is dictionary_name[key]. This will raise a KeyError if the key is not found, so you can use try/except instead of checking ahead of time and doing if/else:

nums = {1: 'One', 2: 'Two', 3: 'Three'}
print ('Type 1, 2, or 3: ')
user = int(input())

try:
    print(f"{user} is the digit you typed {nums[user]}")
except KeyError:
   print('Goodbye!')

If you don't want this code to raise a ValueError on an invalid integer input, you can just use strings as the dictionary keys:

nums = {'1': 'One', '2': 'Two', '3': 'Three'}
print ('Type 1, 2, or 3: ')
user = input()
Samwise
  • 68,105
  • 3
  • 30
  • 44
0

Here it is. You can add error capture to it, but that's probably for a future lesson:

numbers = [1, 2, 3]
num_words = ['One', 'Two', 'Three']
print('Type a number from 1 -3: ')
user = int(input())
if user in numbers:
  print(f"You typed: {num_words[numbers.index(user)]}")

#output:
Type a number from 1 -3: 
2
You typed: Two
pakpe
  • 5,391
  • 2
  • 8
  • 23