Functions in Python: Complete Guide with Syntax, Examples, and Practice Tasks
Master functions in Python with this beginner-friendly guide. Learn how to define functions, use return statements, default and keyword arguments, and solve practical coding tasks with real-world examples.
Table of Contents
- What is a Function?
- How to Write a Function
- Return Statement
- Default Arguments
- Keyword Arguments
- Tasks
1. What is a Function?
A function is a block of reusable code that performs a specific task. It's reusable, which means you can call it multiple times in your program. This helps to organize your code, make it more readable, and avoid repetition.
Why Do We Use Functions?
We use functions in Python for several reasons:
- Code Reusability: You can call a function multiple times instead of repeating code. This saves time and effort.
- Modularity: Breaking down a large program into smaller, manageable chunks (functions) makes it easier to understand and maintain.
- Avoiding Repetition: Functions prevent you from writing the same code over and over, reducing errors and improving efficiency."
2. How to Write a Function
To define a function, you use the def keyword followed by the function name, parentheses for parameters, and a colon. The code block that defines the function is indented.
Syntax:
def function_name(parameters):
# Function body
# Code to be executedExample 1: Defining and Calling a Function
def greet(name):
print("Hello,", name + "!")
# Calling the function
greet("Ahmad") # Output: Hello, Ahmad!Explanation:
def greet(name):defines a function namedgreetthat takes one parameter,name.print("Hello,", name + "!")is the function body, which prints a greeting message using the provided name.greet("Ahmad")calls the function with the argument "Ahmad".
Key Points:
- Parameters: These are variables passed to the function when it's called. For more details, See Parameters and Arguments in Python Functions
- Return Value: A function can optionally return a value using the
returnstatement. - Docstrings: It's good practice to include a docstring (a string that explains the function's purpose) after the function definition.
3. Return Statement
- Functions can return values using the
returnkeyword.
Example 2: Function with a Return Value
def add(x, y):
return x + y
result = add(3, 5)
print(result) # Output: 84. Default Arguments
- You can assign default values to parameters, which makes them optional when calling the function.
Video: Learn How to Use Default Parameters in Function Definition
Example 6.3:
def greet(name, message="Hello"):
print(f"{message}, {name}!")
greet("Alice") # Uses default message "Hello"
greet("Alice", "Hi") # Overrides default with "Hi"5. Keyword Arguments
- Python allows you to specify arguments by name, making your code more readable.
Example 6.4:
def multiply(a, b):
return a * b
result = multiply(b=3, a=5) # You can specify arguments in any order6. Tasks
Task 6.1: Create a Function to Calculate the Area of a Rectangle
Function Requirements:
- Define a function named
calculate_areathat takes two parameters:lengthandwidth. - The function should calculate the area of the rectangle (Area = Length × Width) and return the result.
Input:
- Length (a positive float or integer)
- Width (a positive float or integer)
Output:
- The area of the rectangle (a float)
Expected Output
The area of the rectangle with length 5 and width 3 is: 15
Additional Test Cases
-
Input:
length = 7,width = 2- Output:
The area of the rectangle with length 7 and width 2 is: 14
- Output:
-
Input:
length = 10.5,width = 4.2- Output:
The area of the rectangle with length 10.5 and width 4.2 is: 44.1
- Output:
Task 6.2: Create a Function to Check if a Number is Even or Odd
Function Requirements:
- Define a function named
is_eventhat takes one parameter:number. - The function should determine if the number is even or odd.
- It should return the string
"Even"if the number is even, and"Odd"if the number is odd.
Input:
- A single integer (positive or negative)
Output:
- A string: either
"Even"or"Odd"
Expected Output
The number 4 is: Even
Additional Test Cases
Encourage beginners to test the function with various numbers:
-
Input:
num = 7- Output:
The number 7 is: Odd
- Output:
-
Input:
num = -2- Output:
The number -2 is: Even
- Output:
-
Input:
num = 0- Output:
The number 0 is: Even
- Output:
Task 6.3: Basic Default Argument Task
- Task: Write a function
greetthat takes a name as an argument and a greeting message with a default value of "Hello". If no greeting is provided, the function should use "Hello." - Example:
greet("Alice")should output"Hello, Alice!"andgreet("Alice", "Good morning")should output"Good morning, Alice!"
Task 4: Create a Function with Multiple Defaults and Modify One
- Task: Write a function
calc_pricethat acceptsprice,tax=0.05, anddiscount=0. Calculate the final price after applying tax and discount. Test with various keyword arguments to see how changes affect the result. - Example:
calc_price(100),calc_price(100, discount=0.1),calc_price(100, tax=0.07, discount=0.1)
video: Guard Statements in Python: Explained Simply
Task 5: Fix the Errors
- Fixing Errors in Function Calls and Assignments
def greet():
print("Hello World!")
greeting = greet- Which of the following will cause a syntax error due to incorrect indentation in Python?
A)
print("Hello World!")B)
def my_function():
print("Hello World!")C)
if x == 10:
print("x is 10")D)
x = 10Answer: B