Functions (def)
Imagine you have a robot that knows how to make a sandwich. Instead of telling the robot every single step (get bread, add jam, close bread) every day, you just give that whole process a name: "MakeSandwich." Now, whenever you say that name, the robot does the job! In Python, we call this a function.
What is a Function?
A function is a reusable block of code that performs a specific task.
-
The def Keyword: We use this to "define" or create our function.
-
Called to Action: A function sits quietly in your code and only runs when it is called by its name.
-
Organization: They help you break a giant, messy program into small, easy-to-read "blocks."
Real-World Function Scenarios
-
ATM Machine: A function checks your account balance whenever you press the button.
-
Calculator: A function runs the math for addition or subtraction.
-
Login System: A function checks if your username and password are correct.
-
School Software: A function calculates your final grade and prints your report card.
How it Looks (Syntax & Examples)
The Pattern:
def function_name():
# code block goes here
Example 1: The Greeting Machine
def greet():
print("Hello Students")
# Calling the function to make it work
greet()
Output: Hello Students
Example 2: The Math Machine
def square():
print(5 * 5)
square()
Output: 25
Summary:
-
Stop Repeating: If you find yourself typing the same code twice, turn it into a function instead.
-
Clean Code: Functions make your program look professional and organized.
-
Easy Fixes: If there is a mistake, you only have to fix it once inside the function, and it's fixed everywhere!