Introduction
Functions are reusable blocks of code that perform a specific task. They help in organizing code into manageable sections, improving readability, and promoting code reuse. Functions can take inputs, perform operations, and return outputs. In Python, functions are defined using the def
keyword.
Syntax
def function_name(parameters):
# block of code
return value
def
: Keyword to define a function.function_name
: Name of the function.parameters
: Comma-separated list of parameters (optional).return
: Keyword to return a value from the function (optional).
Example
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
Output:
Hello, Alice!
Types of Functions
- Built-in Functions: Functions that are pre-defined in Python (e.g.,
print()
,len()
). - User-defined Functions: Functions that are defined by users to perform specific tasks.
Creating a Simple Function
A simple function can take no parameters and perform a basic task.
Example
def say_hello():
print("Hello, World!")
say_hello()
Output:
Hello, World!
Functions with Parameters
Functions can take parameters to perform tasks using the input values.
Example
def add(a, b):
return a + b
result = add(5, 3)
print(result)
Output:
8
Functions with Default Parameters
Functions can have default parameter values, which are used if no arguments are provided during the function call.
Example
def greet(name="Guest"):
return f"Hello, {name}!"
print(greet("Alice"))
print(greet())
Output:
Hello, Alice!
Hello, Guest!
Returning Values from Functions
Functions can return values using the return
statement.
Example
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result)
Output:
20
Recursive Functions
A recursive function is a function that calls itself. It is useful for solving problems that can be broken down into smaller, similar problems.
Example: Factorial Function
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Output:
120
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda
keyword. They are often used for short, simple operations.
Example
add = lambda x, y: x + y
print(add(3, 5))
Output:
8
Practical Examples Using Functions
Example 1: Check if a Number is Prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print(is_prime(7))
print(is_prime(10))
Output:
True
False
Example 2: Calculate Fibonacci Sequence
def fibonacci(n):
sequence = [0, 1]
while len(sequence) < n:
sequence.append(sequence[-1] + sequence[-2])
return sequence
print(fibonacci(10))
Output:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Example 3: Find the Maximum Number in a List
def find_max(numbers):
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
print(find_max([10, 20, 4, 45, 99]))
Output:
99
Example 4: Convert Celsius to Fahrenheit
def celsius_to_fahrenheit(celsius):
return (celsius * 9/5) + 32
print(celsius_to_fahrenheit(25))
Output:
77.0
Example 5: Count the Number of Vowels in a String
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
print(count_vowels("Hello, World!"))
Output:
3
Conclusion
Functions are an essential part of Python programming, enabling code reuse, organization, and readability. By understanding how to define and use functions, including built-in functions, user-defined functions, and lambda functions, you can write more efficient and maintainable code. The provided examples demonstrate practical applications of functions in various contexts.