Exercise on Dictionaries

Create a program with a predefined dictionary for a person. Include the following information: name, gender, age, address and phone.

Ask the user what information he wants to know about the person (example: "name"), then print the value associated to that key or display a message in case the key is not found.

Solution

Code:

person = {"name": "kelvin", "gender": "M", "address": "Buokrom Estate", "phone": "0234567890"}

Key = input("What information do you want to know about the person? ")

result = person.get(Key, "That information is not available")

print(result)

Output:
What information do you want to know about the person? name
Kelvin
===== RESTART: C:\Users\ameny\OneDrive\Desktop\Python.course\Ex.dict.py =====
What information do you want to know about the person? children
That information is not available
>>> 

What happens when the user types a small letter, for example, a name?

It will return: That information is not available, and why is that? Because Python is case-sensitive, if the user types it like this: NAME instead of name, that key is not going to be found, so let's see how to solve that. Let's go back to the program and use the lower method. Which would be right by the input function, where the user will type the specific information he/she wants.












So our problem is solved. There you have the solution for this exercise. If you have any questions, just leave them in the comment section. See you in our next tutorial! Good luck.





No comments:

Post a Comment

Python Programming Tutorial 15

 Error Handling Anytime we work with user input, we should make sure not only the data is valid and within the range we want, like what we d...