Intro to Computer Science / Unit 7: Functions
7.1 Defining and Calling Functions
Notes
A function is a named block of code that does one job. You define it with def and call it by name.
def greet():
print("Hello!")
print("Welcome.")
greet()
greet()
- This prints both lines twice, because the function is called twice.
- Defining a function does not run it. Nothing happens until you call it.
- Functions make code reusable, shorter and easier to test.
- Function names follow the same rules as variable names; the body is indented.
Practice
What does a
def statement do?def defines the function. It only runs when called.
How many lines are printed by the code above?
The function prints 2 lines and is called twice, so 4 lines are printed.
What is the main benefit of putting repeated code into a function?
Calling one function replaces repeated copies of the same code.
Ready for more? Take the Unit 7 test.