Skip to main content
Text ready — video coming soon

Read your first Python function

Welcome. If Python is unfamiliar, there is nothing you were supposed to learn before arriving here. The chapter overview promised a small beginning. I will keep that promise with a function that turns a number and a title into a chapter label.

By the end, you will be able to:

  • Follow a value from an input to a result.
  • Distinguish a name from the value it refers to.
  • Explain why returning a result and displaying it are different.
  • Predict a small change before asking the AI to run it.

You can read this lesson without installing anything. In the next lesson, we will put the code in a file and run it.

Give a repeated instruction a name​

Imagine preparing the contents page of a book. Each entry needs the same shape: the word “Chapter”, a number and a title. Writing a separate instruction for every entry invites small inconsistencies.

A function groups instructions under a name so you can ask for the same work again. Here is our first one:

def chapter_label(number, title):
return f"Chapter {number}: {title}"

label = chapter_label(1, "Python and Roots")
print(label)

The displayed result is:

Chapter 1: Python and Roots

Read the first line as “define a function named chapter_label”. The names inside its brackets, number and title, are parameters: names through which the function receives its inputs. The colon ends the opening line. The spaces before return show that the instruction belongs inside the function.

return sends a result back to whoever called the function. The text after it begins with f, which allows Python to insert values inside the braces. This is an f-string, a string with places for values. With number equal to 1 and title equal to "Python and Roots", those two places become the values you see in the output.

Writing def stores the function's instructions; it does not carry them out immediately. The work begins at chapter_label(1, "Python and Roots"). That is a call, an instruction to run a function. The supplied values are its arguments. The first argument goes to number, and the second goes to title.

Finally, label = ... gives the returned value a name, and print(label) displays it. print is a function Python already provides.

Keep names and values separate​

In label = "Python and Roots", the text is the value. label is a name referring to it. The equals sign assigns a value to a name; it does not ask whether two things are equal.

You can later give a name another value:

title = "Python and Roots"
title = "Python and Branches"
print(title)

This displays Python and Branches. Python runs the lines in order, and the second assignment changes what title refers to. It does not rewrite every earlier string in the program.

Values have types, which describe the kind of value and the operations it supports:

ExamplePython typeMeaning
7intA whole number
2.5floatA number represented with limited precision
"7"strText, even when it contains digits
True or FalseboolA true-or-false value
NoneNoneTypeA value often used to mean “no result here”

7 + 1 produces 8. "7" + "1" produces "71", because adding strings joins their text. "7" + 1 raises an error: these addition operations do not accept that mixture of text and a number. Convert deliberately if the requirement calls for it.

Converting a value is an explicit decision. int("7") produces the integer 7; int("seven") fails because those characters are not an integer representation. When you read code receiving user input, check which conversion it makes and what happens if conversion fails. We will handle that failure properly later in this chapter.

Floats also need care. Some values, including 2.5, are exact; many decimal fractions are not. For example, 0.1 + 0.2 == 0.3 is False because the stored binary approximations do not add to exactly the same value. A solution comparing measured quantities needs an appropriate tolerance. Exact stored amounts need a deliberate representation and rounding rule. The practical question is whether the comparison matches the intended meaning, rather than whether the displayed number looks right.

Read text operations from the inside out​

Our titles may arrive with spaces around them. Python strings provide named operations called methods. A method is called through a value using a dot:

title = " Python and Roots "
clean_title = title.strip()
print(clean_title)

strip() returns text with surrounding whitespace removed. It does not remove the spaces between the words. It also does not alter the original string: strings cannot be changed in place. That is why the example gives the result a name.

The reading skill is to identify the input, the operation and the returned result. We will use split and join after you have met the list of text pieces they work with.

You can also supply arguments by name:

label = chapter_label(title="Python and Roots", number=1)

The names make the intended mapping clear even though the arguments appear in a different order. A default supplies an input when the caller omits it:

def greeting(name="reader"):
return f"Welcome, {name}."

greeting() returns "Welcome, reader."; greeting("Amina") returns "Welcome, Amina.". Defaults are useful, but they can also hide a missing input. Ask whether a default matches the requirement.

Notice when a function gives nothing back​

Now consider a plausible mistake:

def chapter_label(number, title):
print(f"Chapter {number}: {title}")

label = chapter_label(1, "Python and Roots")
print(label)

This displays the chapter label, followed by None. The inner print displays text, but the function has no return. A Python function that reaches its end without returning a value returns None.

The screen looked partly correct, yet another part of the program received the wrong result. This is a useful first review habit: check what a function returns, not only what appears on screen. A book assistant needs the returned label to form its answer; visible text alone does not meet that requirement.

Try a prediction before running​

For the language details, the Python tutorial on values and strings and defining functions are the source references for this lesson.

Close the explanation above and answer these in your own words:

  1. What does chapter_label(2, "Python and Branches") return in the first version?
  2. Why are 7 and "7" different inputs?
  3. If a function only calls print, what does its caller receive when it ends?
  4. What would you ask the AI to preserve while removing surrounding spaces from a title?
Check your reasoning after you have tried
  1. The string Chapter 2: Python and Branches.
  2. One is a whole number; the other is text. Their supported operations differ.
  3. None, unless an explicit return supplies a different value.
  4. Keep the title's words and internal spaces, and return the cleaned text rather than only displaying it. For this change, space-only input should return an empty string, because removing all surrounding spaces leaves no characters.

Ask the AI for that small cleaning change and explain its proposed result before running it. You do not need to recall the punctuation from memory. You need to account for the behaviour.

The next lesson turns these lines into a file you can run and gives you a way to read the first error without losing your place.