Python Basics: Your First Programs
Functions
In this lesson you will
- Define and call a function with parameters and a return value
- Use default and keyword arguments
- Explain local and global scope
Introduction
If you make tea every morning, you don't re-learn the steps each day. You just say "make tea". A function is a named recipe: you write the steps once and run them whenever you like. Functions are how programs stay short and avoid repeating themselves.
Defining and calling
Use def, a name, brackets and a colon. The indented lines are the body.
Defining a function does not run it. It runs each time you call it with brackets.
Parameters
Parameters are inputs, like blanks in the recipe. The values you pass in are called arguments.
Returning a value
print shows something to the person. return hands a value back to the code that called the function, so it can be stored and used.
When Python reaches return, the function ends immediately. A function with no return gives back None.
Quick quiz
What is the difference between print and return in a function?
Default and keyword arguments
A parameter can have a default value, used when the caller leaves it out.
You can pass arguments by name, in any order. This makes calls easier to read.
Returning several values
A function can return a tuple, which you can unpack.
Scope: where variables live
A variable created inside a function is local: it exists only while the function runs.
Functions can read variables defined outside, but should receive what they need as parameters and give results with return. That keeps them easy to understand and test.
Docstrings
The first line of a function body can be a string describing it. This is the function's docstring. The built-in help() shows it.
Functions calling functions
Small functions that do one job can be combined.
Quick quiz
What does a function with no return statement give back?
Try it yourself
Write a function is_palindrome(word) that returns True if the word reads the same backwards (like "level") and False otherwise. Hint: a string reversed is word[::-1].
Summary
def name(parameters):defines a function, andname(arguments)calls it.returnsends a value back and ends the function. Without it you getNone.- Parameters can have defaults, and arguments can be passed by name.
- Variables made inside a function are local. Pass in what you need and return the result.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading