Module 3 Lesson 2: Defining and Calling Functions
Master the syntax of functions in Python. Learn how to use the 'def' keyword, the importance of colons, and how to execute your code.
Module 3 Lesson 2: Defining and Calling Functions
Creating a function in Python consists of two parts: The Definition (telling Python what the function does) and The Call (telling Python to run it right now).
Lesson Overview
In this lesson, we will cover:
- The
defKeyword: How to start a function. - The Body: Indentation and the logic inside.
- Calling the Function: Making it run.
- Execution Flow: Understanding how Python jumps around your code.
1. Defining a Function
To define a function, we use the def keyword, followed by the name we want to give it, parentheses (), and a colon :.
def say_hello():
# Everything indented here is part of the function
print("Hello from inside the function!")
print("Hope you're having a great day!")
Naming Rules: Function names follow the same rules as variables (lowercase, underscores between words, e.g., calculate_tax).
2. Calling a Function
Simply defining a function does nothing. If you run the code above, your screen will be blank. You have to "call" it by typing its name with parentheses.
# The Definition
def greet():
print("Welcome to Python!")
# The Call
greet()
3. The Flow of Execution
In a normal script, Python runs line 1, 2, 3... but with functions, it "jumps" around.
print("1. This is the first line.")
def my_func():
print("3. This is inside the function.")
print("2. This is after the definition.")
my_func() # Python jumps back up to the definition here!
print("4. This is the final line.")
Output:
1. This is the first line.
2. This is after the definition.
3. This is inside the function.
4. This is the final line.
Practice Exercise: The Function Script
Create a file named simple_functions.py.
- Define a function named
introductionthat prints your name and your dream job. - Define a second function named
current_goalthat prints what you want to achieve by the end of this course. - Call both functions in order.
- Call the
introductionfunction three times in a row and notice how you didn't have to re-type theprintstatements!
Quick Knowledge Check
- What keyword is used to start a function definition?
- Why doesn't the code inside a function run as soon as Python sees it?
- How do you tell Python that a line of code belongs to a specific function?
- Can you call a function before you have defined it (at the top of the file)?
Key Takeaways
defis used to define functions.- Function names must be followed by
():. - Indentation defines the "body" of the function.
- A function only executes when it is "called" by its name.
What’s Next?
Our functions are currently static—they always do the exact same thing. But professional functions usually take data and give something back. In Lesson 3, we’ll explore Parameters and Return Values!