-1

I wrote s small script to iterate through a dictionary in python3 that works just fine. I was working in a different machine that only had python2.4 installed. I copied the script and ran and now the code is not entering the if-statement within the for loop. I am assuming this is just a version discrepancy.

I had tried to look online to see what some differences could be between versions. Closest I have come to is 'dict.iterkeys()'

tests = {'1':'test1','2':'test2'}

answer = input('which test? ')

for test in tests:
    if test == answer:
        print(tests[test])

The expected output is for the tests I want to be printed. However, in python version 2.4 it is not entering the if-statement at all. In python3 this script works just fine.

Any insight helps.

Thanks!

  • In Python 2.4, what is `test`? Put in a `print` statement to trace the values you're checking. – Prune Sep 25 '19 at 00:15
  • Hi, `test` is the variable that will iterate through the dict. I have put in a print statement to track the values. Both inside the `for` loop and inside the `if` statement. That is how I figured out it is not entering the `if` statement. – Jaime Perez Sep 25 '19 at 00:20
  • Try using `answer = int(input('which test? '))` on python3 – Jab Sep 25 '19 at 00:26
  • @Jab Note that dict keys are strings, not ints – Selcuk Sep 25 '19 at 00:44
  • My mistake I fixed in my answer – Jab Sep 25 '19 at 12:56

1 Answers1

1

Python3 replaced the old input statement with the functionality of python 2’s raw_input. It used to evaluate the input now it’s passed as a string for safety.

Replace the line: (py3)

answer = input('which test? ')

With: (py2)

answer = raw_input('which test? ')

Or:

answer = str(input('which test? '))

Refer to PEP3111 for more details.

Jab
  • 26,853
  • 21
  • 75
  • 114