+ 1
Complete the program to get a string as input , search for the name in the list of contacts and output the age of the contact
contacts = [ ('James', 42), ('Amy', 24), ('John', 31), ('Amanda', 63), ('Bob', 18) ] Please help Python Intermediate Tuple Problem
3 odpowiedzi
+ 1
Try this solution:
contacts = {
'James': 42,
'Amy': 24,
'John': 31,
'Amanda': 63,
'Bob': 18
}
input_name = input("Enter a name: ")
age = contacts.get(input_name)
if age is not None:
print(f"The age of {input_name} is {age}.")
else:
print(f"{input_name} was not found in contacts.")
The contacts variable is a dictionary where the names are the keys and the ages are the values. The get method of the dictionary is used to retrieve the age associated with the input name. If the name is not found, it returns None, which is then handled accordingly in the code.
0
Thanks