Building from Pieces

Overview


In Part 2, you learned to collect an unknown amount of input, store several values in lists, process them with loops, and build new results one item at a time.

From Loops to Functions

A longer program can become difficult to read even when each of its loops works correctly.

Functions let you give a piece of behavior a name. A function can receive information, perform one job, and return a result. In this part, you will use functions to divide longer programs into understandable responsibilities.

Consider this program, which collects measurements and then summarizes them:

measurements = []
while True:
text = input("Measurement, or done: ").strip().lower()
if text == "done":
break
measurement = float(text)
measurements.append(measurement)
usable = []
for measurement in measurements:
if measurement >= 0:
usable.append(measurement)
if len(usable) == 0:
print("No usable measurements")
else:
total = 0
for measurement in usable:
total = total + measurement
average = total / len(usable)
print(f"Average: {average}")

For now, assume that every entry other than done is a valid number. Later in this part, you will learn how to respond when a user types something that cannot be converted to a number.

In Part 2, you divided programs like this into phases. This program has four jobs:

  • reading input;
  • selecting usable values;
  • calculating a summary;
  • presenting the result.

Once a function works, the rest of the program can use it without repeating its implementation.

You have already used functions throughout the course:

print("Hello")
name = input("Name: ")
length = len(name)

Someone else defined print, input, and len. In this part, you will begin defining functions of your own.

Functions also make another important programming habit much easier: testing. Instead of running an entire interactive program and manually checking everything, you can call one calculation function with a known input and check whether it returns the expected result.

You will continue to check explanations and AI-generated code against a program’s behavior. For a function, ask:

Does this function actually satisfy the behavior that was requested?

After working through this part, you should be able to write, trace, test, and explain programs built from functions, with clear inputs, results, and handling of invalid input.

The structure of this part is as follows:

A useful rhythm for this part is:

  1. read each chapter in order;
  2. type and run the examples rather than only reading them;
  3. complete the exercises as you go;
  4. when a function call is confusing, trace the values passed in, any changes made, and the returned result;
  5. when you write a function, test it with more than one kind of input;
  6. finish with the recap and feedback.

After Chapter 4, pause to check that you can trace a function call, distinguish printing from returning, and explain whether a list argument changes. Those ideas will help you build the larger programs later in the part.

When writing a function, ask three questions:

What is this function responsible for?
What information does it need?
What does it give back?

Those questions will remain useful long after the exact syntax has become familiar.

However, before starting, please complete the next activity first, which is a recap of lists and loops.

LEIA activity: lists and loops

In this activity, you will practise lists and loops by completing a programming task with an AI simulated client on the LEIA platform. You will be randomly assigned to a text-based or voice-based version. The study explores how these ways of interacting support programming and learning.

This is part of a research study. You can read more from the participant information sheet and the privacy notice. Research participation is voluntary; your research consent choices do not affect the course points available for these exercises.

Do not enter personal or sensitive information in the LEIA platform. This includes names, personal email addresses, student numbers, and any other identifying details in your messages, speech, code, or comments.

The voice-based version requires a microphone and speakers or headphones. If you have technical problems or cannot use the voice-based version, contact the course staff for access to the text-based version.

LEIA Conversation Viewer Link

0 / 5 points

Follow these steps to complete the LEIA activity and submit your Conversation Viewer Link:

  1. Open the List + Loop activity. In the window that opens, click Open link.
  2. The next page has an automatically generated test email address ending in @test.com. Do not modify this email address or the Replication code, and do not enter your own email address. Click Start session.
  3. The activity begins with a research consent question. Choose either Yes, I consent or No, I do not consent. Either choice lets you complete the activity and receive the same course points.
  4. Follow the activity instructions and finish the activity. At the end, copy the Conversation Viewer Link provided by LEIA.
  5. Paste the complete link into the answer field below, without adding any other text, to receive 5 course points.
  6. Once your link is accepted, the survey below will unlock automatically.

Once you have completed the activity and submitted your Conversation Viewer Link, please complete the survey below.

Survey about the LEIA activity

0 / 5 points

The first question asks for your consent to use these survey responses for research. Leaving the consent question unanswered is treated as not consenting.

All questions are optional. You may select “No, I do not consent”, skip any questions, or leave the entire form blank. Submit this survey step to receive 5 course points, regardless of your consent choice or the content of your answers. Regardless of your consent choice, please try to answer the questions as honestly as possible. Your consent choice and the content of your answers do not affect these points.