Defining Functions
Defining Functions
As programs grow, you may need to use the same code many times.
Writing the same code again and again takes time and makes programs harder to manage.
Functions solve this problem.
A function lets you place code inside a reusable block. You can run that block whenever you need it.
What Is a Function?
A function is a group of code with a name.
That code is saved and can be used later.
Think of a function like a machine button:
- Press the button
- The machine does its job
When you call a function, Python runs the code inside it.
Why Functions Matter
Functions help you:
- Reuse code
- Keep programs clean
- Save time
- Organize large programs
- Fix code in one place
Real Example Without a Function
print("Hello")
print("Hello")
print("Hello")
This works, but repeating code is not the best habit.
Better Example With a Function
def greet():
print("Hello")
greet()
greet()
greet()
Output
Hello
Hello
Hello
Understanding def
The word def is a Python keyword.
It means you are defining (creating) a function.
def greet():
Let’s break it down:
deftells Python a function is startinggreetis the function name()is where extra values can go later:starts the code block
The Code Inside the Function
Indented lines belong to the function.
def greet():
print("Hello")
The spaces before print() are important.
They tell Python this line is part of the function.
Important: Creating Is Not Running
This code creates a function, but does not run it yet.
def greet():
print("Hello")
Nothing happens until you call it.
Calling a Function
To run the function, type its name followed by brackets.
greet()
This tells Python to run the saved code.
Another Example
def welcome():
print("Welcome to Python")
welcome()
Output
Welcome to Python
Common Beginner Mistakes
Forgetting the Brackets
Wrong:
greet
Correct:
greet()
Forgetting Indentation
Wrong:
def greet():
print("Hello")
Correct:
def greet():
print("Hello")
Code Along
def show_name():
print("Sam")
show_name()
Output
Sam
Mini Challenge
Build a greeting function.
Steps:
- Create a function called
hello - Inside the function, print:
Hello Student - Call the function two times
Expected output:
Hello Student
Hello Student
Real World Use Case
Programs use functions for calculations, login checks, emails, reports, games, and many repeated tasks.
Quiz
- What is a function?
- Which keyword creates a function?
- Does a function run when it is created?
- How do you run a function?
Assignment
Create a function called bye that prints Goodbye, then call it three times.
Summary
You learned that functions are reusable blocks of code, how to create them with def, and how to run them by calling the function name.