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!

Check your knowledge

Quickly verify what you've learned from this tutorial.

Question 1

What keyword must you use to start a function in Python?

In Python, def is used to define a new function block.

Question 2

When does the code inside a function actually run?

A function is like a tool that stays in the toolbox until you call it to perform a task.

Question 3

Why are functions helpful for "Debugging" (fixing errors)?

Since functions promote reusability, fixing a bug inside the function fixes it everywhere that function is used.

Question 4

What is the best name for a function that calculates a student's score?

Using meaningful names helps other programmers (and your future self) understand what the function does.

Question 5

Which of the following is NOT a benefit of using functions?

Functions actually help make programs more efficient and easier to manage, not slower.

Congratulations!

You've successfully mastered the knowledge check for "Functions (def)."

For more questions and practice, click the link below:

Practice More Questions
Previous Topic Functions Next Topic Function Parameters