Card 7: Functions (Reusable Code)

A function is a block of organized, reusable code that performs a single, specific action. It's like having a recipe for a special dish. Instead of writing the recipe every time, you just refer to it by name.

1. What is a Function?

Story: A function is a named set of instructions. You can use it again and again without rewriting the code. This makes your code cleaner and easier to manage.

Analogy: A recipe for making "Pesarattu." You follow the same steps every time you want to make it.

2. Defining a Function

Story: You create a function using the `def` keyword, followed by the function's name and parentheses `()`. The code inside the function is indented.

The Code: def greet(): print("Namaste, Andhra Pradesh!")

3. Calling a Function

Story: To use the function, you "call" it by writing its name followed by parentheses.

The Code: greet() would run the code inside the function and print "Namaste, Andhra Pradesh!".

4. Functions with Parameters

Story: You can make functions more flexible by giving them information. These are called parameters.

The Code: def greet_person(name): print("Namaste,", name). Then you can call it with `greet_person("Praveen")`.

Python Code with Functions:

# Define a function to calculate the area of a rectangle
def calculate_area(length, width):
  area = length * width
  print("The area is:", area)

# Call the function with different values
calculate_area(10, 5)
calculate_area(20, 15)
            

Key Technical Terms

Knowledge Check

What is the main benefit of using a function?