Understanding def
Statements in Python
The def
statement in Python is used to define a function, which is a block of reusable code designed to perform a specific task. Functions make programs more modular, reusable, and easier to understand.
Why Use Functions?
Functions help:
- Avoid repeating code (reduces redundancy).
- Break a program into smaller, manageable parts.
- Make the code reusable and efficient.
Real-Life Example:
Think of a washing machine: You load the clothes, select the mode, and press start. The machine performs its task (washing) and stops when done. Similarly, in programming, you call a function to perform a specific task.
Syntax of def
def function_name(parameters):
"""Optional docstring: Describe the function"""
# Code block
return result # Optional
Components:
def
: Keyword to define a function.function_name
: Name of the function (should follow variable naming conventions).parameters
: Optional input values to the function (inside parentheses).:
: Indicates the start of the function body.- Function Body: Indented block containing the code to execute.
return
: Optional statement to send the result back to the caller.
Example: Simple Greeting Function
def greet():
"""This function prints a greeting message."""
print("Hello! Welcome to PythonForAll.")
How to Call a Function
greet() # Output: Hello! Welcome to PythonForAll.
Adding Parameters
Functions can take inputs (parameters) to perform operations dynamically.
Example: Greeting a User
def greet_user(name):
"""This function greets the user by name."""
print(f"Hello, {name}! Welcome to PythonForAll.")
greet_user("Rhea") # Output: Hello, Rhea! Welcome to PythonForAll.
Returning Values
Functions can return results using the return
statement.
Example: Add Two Numbers
def add_numbers(a, b):
"""This function returns the sum of two numbers."""
return a + b
result = add_numbers(5, 7)
print("Sum:", result) # Output: Sum: 12
Default Parameters
Default parameters allow you to specify a default value for a function argument.
Example: Default Greeting
def greet_user(name="Guest"):
"""This function greets the user by name, or uses 'Guest' as default."""
print(f"Hello, {name}! Welcome to PythonForAll.")
greet_user() # Output: Hello, Guest! Welcome to PythonForAll.
greet_user("Nitya") # Output: Hello, Nitya! Welcome to PythonForAll.
Using Multiple Parameters
A function can accept multiple parameters separated by commas.
Example: Calculating Area
def calculate_area(length, width):
"""This function calculates the area of a rectangle."""
return length * width
area = calculate_area(5, 3)
print("Area:", area) # Output: Area: 15
Functions with No Return
Some functions perform tasks without returning a value (e.g., printing messages).
Example: Logging
def log_message(message):
"""This function logs a message."""
print(f"Log: {message}")
log_message("Function executed successfully!")
def
with Loops and Conditional Statements
You can use loops and conditions inside functions to handle complex logic.
Example: Check Even or Odd
def check_even_odd(number):
"""This function checks if a number is even or odd."""
if number % 2 == 0:
return "Even"
else:
return "Odd"
print(check_even_odd(10)) # Output: Even
print(check_even_odd(7)) # Output: Odd
Advanced: Functions with Variable Arguments
Example: Sum of Multiple Numbers
def sum_numbers(*args):
"""This function calculates the sum of multiple numbers."""
return sum(args)
print(sum_numbers(1, 2, 3, 4)) # Output: 10
Scope of Variables
Variables inside a function are local to that function unless explicitly declared global.
Example: Local and Global Variables
x = 10 # Global variable
def multiply_by_two():
"""This function multiplies the global variable by 2."""
global x
x *= 2
multiply_by_two()
print("Global x:", x) # Output: Global x: 20
Key Takeaways
- The
def
statement is essential for defining reusable functions. - Use parameters for flexibility and
return
for results. - Functions help make code modular and easy to debug.
Try It Yourself
Problem 1: Create a Function to Find Factorial
Write a function to calculate the factorial of a given number.
Show Code
def factorial(n):
"""This function calculates the factorial of a number."""
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Problem 2: Function to Find the Largest Number
Write a function that accepts three numbers and returns the largest.
Show Code
def find_largest(a, b, c):
"""This function returns the largest of three numbers."""
return max(a, b, c)
print(find_largest(5, 10, 7)) # Output: 10
Problem 3: Function with Default and Variable Arguments
Write a function that takes a name and an optional list of hobbies to display a greeting.
Show Code
def greet_person(name="Guest", *hobbies):
"""This function greets a person and lists their hobbies."""
print(f"Hello, {name}!")
if hobbies:
print("Your hobbies are:", ", ".join(hobbies))
else:
print("You didn't share your hobbies.")
greet_person("Raghav", "Reading", "Coding", "Traveling")