1
switch = {(0,21): 'never have a pension',
          (21,50): 'might have a pension',
          (50,65): 'definitely have a pension',
          (65, 200): 'already collecting pension'}
for key, value in switch:
  a=input()
  if key[0] < a< key[1]:
        print(value)

when I try to execute the program it raise an error

TypeError: 'int' object is not subscriptable.

I don't know how to fix. please help

3 Answers 3

1

When you do for kev, value in switch, you're not getting the tuple and the string - you're getting the two values from the tuple. This is because iterating over a dictionary by default iterates over its keys.

Instead, you want to do for key, value in switch.items().

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

1 Comment

thanks for help... can you u tell me how to take input and print values accordingly as in dictionary.. i am trying but with no success
0

I suppose you would like to do:

while True:
    try:
        a = int(input())
    except ValueError:
        print('not an int, try again')


for k, v in switch.items():
    if k[0] < a < k[1]:
        print(v)

And depending your needs:

>>> [v for k, v in switch.items() if k[0] < a < k[1]]
['might have a pension']

Comments

0

By the way, this is a fairly unpythonic way to do a multi-range test.

Consider this if-elif tree instead:

a = input()

if a < 21:
    msg = 'never have a pension'
elif a < 50:
    msg = 'might have a pension'
elif a < 65:
    msg = 'definitely have a pension'
else:
    msg = 'already collecting pension'

print msg

Advantages: it is simpler to understand, avoids duplicating the endpoints (which are most likely to change), works even if people somehow manage to live past 200, and actually avoids a bug in your original code (where people would already be collecting a pension if they were exactly 21).

Disadvantages: code is longer, and msg and a are repeated. However, this is offset by the fact that you can now implement more customizable and appropriate logic under each case.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.