0

I am fairly new to programming and I've been experimenting with dictionaries in Python. However, I just updated to Python 3.4 and code that was previously usable is not functioning properly after the update. I thought I had cleared most everything up, but now my dictionary seems to be broken.

The code runs fine until I try to call on the dictionary. Here is an example of code that previously worked correctly in Python 2.7:

userPrompt = input("Month: ")

months = {
        1: jan,
        2: feb,
        3: mar,
    }

months[userPrompt]()

It seems to have an issue with that final line. Do I need to write the dictionary differently, or address it differently?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
clickynote
  • 11
  • 1
  • 2
  • 1
    The user input **is always a string** (for changes between 2.x and 3.x, see https://docs.python.org/3/whatsnew/3.0.html#builtins). Either convert your keys to strings, or the input to integers. See e.g. http://stackoverflow.com/q/20449427/3001761 – jonrsharpe Mar 22 '15 at 20:52

1 Answers1

1

Use the following:

int(userPrompt)

to get the integer value of your input string. In python 3, the input function doesn't use the eval function. Instead, it returns the raw string, like python's 2 raw_input function. It's up to the programmer to convert it to an integer.

For example in python2:

>>> type(input())
42
<class 'int'>

In python3:

>>> type(input())
42
<class 'str'>
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57