-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!

5
  • In Python 2.4, what is test? Put in a print statement to trace the values you're checking. Commented Sep 25, 2019 at 0: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. Commented Sep 25, 2019 at 0:20
  • Try using answer = int(input('which test? ')) on python3 Commented Sep 25, 2019 at 0:26
  • @Jab Note that dict keys are strings, not ints Commented Sep 25, 2019 at 0:44
  • My mistake I fixed in my answer Commented Sep 25, 2019 at 12:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Quite the opposite... They should replace it with str(input(...)) instead.
Excuse me lol thanks! Edited.
Thank you. I was not aware of the difference between the input and raw_input functions. My apologies!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.