-1

My purpose is to get two lists into dictionary format and print out the Names whose age is 20. Here is my code. The problem that I am facing is that, after I obtain input from user and it pass to function it does not take effect. I can print out the parameter integer and age separately - it works fine. When it gets to the if function it does not print the name at all. I tried to hard code the integer to 20 - it works but that is not code that I want.

NAMES = ['Alice', 'Bob', 'Cathy', 'Dan', 'Ed', 'Frank','Gary', 'Helen', 'Irene', 'Jack', 'Kelly', 'Larry']
AGES = [20, 21, 18, 18, 19, 20, 20, 19, 19, 19, 22, 19]
list1 = {}

def getinput():
    age=input('Please enter your age')
    return age

def changedict():
    for x in range(len(NAMES)):
        list1[NAMES[x]]=AGES[x]     

def get_names(integer):
    for name, age in list1.items():
        if age == integer:
            print(name)

changedict()
para=getinput()
get_names(para)

If there is any improvement in the code above, like a more simplified version, please comment on it. I also want to know a bit more about the items function. Is there any other way to scan through dictionary without using items?

Dycey
  • 4,767
  • 5
  • 47
  • 86
RandyWong
  • 85
  • 1
  • 9
  • 2
    age (int) is never equal to input (string). Python does not perform any kind of implicit conversions between types. try `return int(age)` in `getinput()`. – Łukasz Rogalski Jul 25 '16 at 09:36
  • 2
    You can create your initial dictionary by zipping together your two lists: `dict(zip(NAMES,AGES))` – Gábor Fekete Jul 25 '16 at 09:56

1 Answers1

2

The input that you get from the user is string type but (as you observed) you need an int type, so just convert it before getinput return:

def getinput():
    age = input('Please enter your age')
    return int(age)
Ohad Eytan
  • 8,114
  • 1
  • 22
  • 31