Python 3.7 : Exercise : Display function

In this small exercise we look at our existing code and notice the same print statements are repeated each time we want to display a person. The goal is simple: extract that repetition into a single function so the program stays clean and easy to read. Take a few minutes, write your own version, then compare it with the correction below.

Building the display function

The function can live anywhere in the file; placement does not matter in Python. We define it with def, give it two parameters (the name and the age), and move the original print calls inside its body. Once the function exists, the calling code becomes a single line per person instead of several lines repeated.

def display(name, age):
    print(name)
    print(age)

display("Titi", 12)
display("Mini", 14)

We run the program again and check the output: the first person prints their name and age, then the second person does the same. Everything still works exactly like before, but the duplicated print logic has disappeared. This is a small but very common refactoring step you will use constantly when writing Python.

The key takeaway is that a function is just a way to package a piece of code under a name so you can call it many times with different values. The two parameters name and age let us reuse the same display logic for any person we want. In the next video we will continue practising with conditions and variables, which combine very naturally with functions like this one.

Summary

This lesson presents a practical exercise on creating a display function in Python to eliminate code repetition. The instructor guides students through building a function that properly handles data output while following Python conventions. The exercise concludes with testing the implemented function to verify it executes correctly with sample data.

Key points

  • Creating a function to eliminate repeated code patterns
  • Understanding function parameters and return values in Python
  • Implementing display functions following Python naming conventions
  • Testing the function with sample data values
  • Verifying function output works as expected

FAQ

What is the main objective of this exercise?

The objective is to create a reusable display function that eliminates code repetition and demonstrates proper Python function structure and conventions.

What parameters does the display function accept?

The display function accepts data parameters such as name and age, which are then processed and displayed by the function.

How is the function tested in this exercise?

The function is tested by calling it with sample values (such as name and age data) and verifying that it produces the expected output without errors.