-2

Could someone help me with this? No matter what number I put I get the same answer/output

items = {'1': '2', '3': '4', '5': 'a'}
choice = input("Select a number: ")
if choice in items:
    the_choice = items[choice]
    print('you go right')
else:
    print('you go left')
giliev
  • 2,938
  • 4
  • 27
  • 47
james548
  • 1
  • 1
  • 2
    Please explain what behavior you're hoping for from your code. Also give examples of input and the output you expect – Sam Hartman May 28 '17 at 18:33
  • 4
    That's a perfectly valid code, I'm guessing you're using Python 2.x and it evaluates your input (into an int, for example) - if that's the case, try using `raw_input` instead. – zwer May 28 '17 at 18:37
  • just following up on @zwer , `raw_input` converts any input into a string, and thus can match the strings in your list: _The function then reads a line from input, converts it to a string_ , [source](https://docs.python.org/2/library/functions.html#raw_input) – patrick May 28 '17 at 19:33
  • I'm hoping that when you type 1,2,3,4,5 or a "you go right " pops up if you don't then "you go left" – james548 May 28 '17 at 21:08

1 Answers1

0

According to the comment, you want that if the user types a number between 1 and 5 or 'a' it's print "you go right". So items should be a list of strings, not a dictionnary nor a set. List are defined by []. Then, it's always best to cast your inputs (str(input()) to cast to a string for example). Finally, indices in Python starts at 0 not 1, consequently you should assign items[choice-1] instead of items[choice] (else it would generate an error if the user's choice is 5). I also added another if statements as items['a'] means nothing for a list.

Which gives:

items = ['1', '2', '3', '4', '5', 'a']
choice = str(raw_input("Select a number: "))
if choice in items:
    if choice is not 'a':
        the_choice = items[int(choice)-1]
    print('you go right')
else:
    print('you go left')

It will return you go right if the user writes 1,2,3,4,5 or 'a' ; you go left for all the other cases.

Nuageux
  • 1,668
  • 1
  • 17
  • 29
  • I double check with Python 2.7.6 and 3.4.3. You just have to change `raw_input` to `input` for the Python 3 versions. But I can't reproduce your problem. Are you sure it is not in another part of your code? – Nuageux Jun 01 '17 at 07:41