Tuesday, November 15, 2022

Dictionaries - Python Programming for Beginners Practice Exercise 9

Exercise 9:

Create a dictionary that contains a list of people and one interesting fact about each of them. Display each person and their interesting fact to the screen. Next, change a fact about one of the people. Also add an additional person and corresponding fact. Display the new list of people and facts. Run the program multiple times and notice if the order changes.

Sample Output:

Jeff: Is afraid of clowns.
David: Plays the piano.
Jason: Can fly an airplane.
Jeff: Is afraid of heights.
David: Plays the piano.
Jason: Can fly an airplane.
Jill: Can hula dance.



Solution:

#!/usr/bin/env python3

def display_facts(facts):
    """Displays facts"""
    for fact in facts:
        print('{}: {}'.format(fact, facts[fact]))
    print()

facts = {
    'Jason': 'Can fly an airplane.',
    'Jeff':  'Is afraid of clowns.',
    'David': 'Plays the piano.'
}

display_facts(facts)

facts['Jeff'] = 'Is afraid of heights.'
facts['Jill'] = 'Can hula dance.'

display_facts(facts)

No comments:

Post a Comment