Python · Beginner level

Beginner level · Module 4: Writing Reusable Functions · Lesson 1 of 3

Defining Functions with Parameters and Return Values

Write functions that take inputs and return results instead of printing everything directly.

In this lesson you will

  • Define and call functions
  • Distinguish return from print

Key concepts

defparameter vs argumentreturn valuedocstring

The lesson

A function is a named, reusable block of code. You define it once with def, give it parameters (the inputs it needs) and use return to send a result back. Calling the function runs its code with the values you pass.

Return is different from print. print shows a value on screen and the program cannot use it afterwards; return hands the value back so it can be stored, compared or passed to another function. Most functions should return results and leave printing to the main part of the program.

Good function names are verbs that describe the job: calculate_total, convert_to_usd, is_valid_phone. If you cannot name a function clearly, it is probably doing more than one job.

Step by step

  1. Define calculate_total(prices) that adds a list of prices and returns the sum.
  2. Define convert_to_usd(amount_ssp, rate) that returns the converted amount.
  3. Call both functions and store the results in variables.
  4. Print the results in one formatted line.

Practice activity

Write calculate_total(prices) and convert_to_usd(amount_ssp, rate) and use them in a short script.

Expected result: Two working functions that return values used elsewhere in the script.

Check your understanding

  1. Why is returning a value usually better than printing inside a function?

    Show answer

    The caller can reuse the value (store, combine, test it); printed output cannot be reused.

  2. What does a function return if it has no return statement?

    Show answer

    None.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.