Python Function Examples
Just getting started with Python? This page is packed with simple, beginner-friendly function examples that help you build a strong foundation.
Functions are reusable blocks of code. On this page, you'll explore how to define and use def functions, pass arguments, use return values, and work with special cases like *args, **kwargs, and lambdas.
1. Basic function definition and call
1. Basic function definition and call
python
# Example 1: Basic function
def greet():
print("Hello from a function")
greet()
# Example 1: Basic function
def greet():
print("Hello from a function")
greet()
2. Function with parameters
2. Function with parameters
python
# Example 2: Function with parameters
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
# Example 2: Function with parameters
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
3. Function with return value
3. Function with return value
python
# Example 3: Return value
def add(a, b):
return a + b
result = add(3, 5)
print("Sum is:", result)
# Example 3: Return value
def add(a, b):
return a + b
result = add(3, 5)
print("Sum is:", result)
4. Default parameter values
4. Default parameter values
python
# Example 4: Default parameters
def greet(name="Guest"):
print(f"Welcome, {name}")
greet()
greet("Eve")
# Example 4: Default parameters
def greet(name="Guest"):
print(f"Welcome, {name}")
greet()
greet("Eve")
5. Keyword arguments
5. Keyword arguments
python
# Example 5: Keyword arguments
def describe_pet(animal, name):
print(f"I have a {animal} named {name}")
describe_pet(name="Tommy", animal="dog")
# Example 5: Keyword arguments
def describe_pet(animal, name):
print(f"I have a {animal} named {name}")
describe_pet(name="Tommy", animal="dog")
6. Variable number of arguments
6. Variable number of arguments
python
# Example 6: *args
def print_numbers(*nums):
for num in nums:
print(num)
print_numbers(1, 2, 3, 4)
# Example 6: *args
def print_numbers(*nums):
for num in nums:
print(num)
print_numbers(1, 2, 3, 4)
7. Function with **kwargs
7. Function with **kwargs
python
# Example 7: **kwargs
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
# Example 7: **kwargs
def print_info(**info):
for key, value in info.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25)
8. Recursive function
8. Recursive function
python
# Example 8: Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
# Example 8: Recursion
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
9. Lambda function
9. Lambda function
python
# Example 9: Lambda
square = lambda x: x * x
print(square(6))
# Example 9: Lambda
square = lambda x: x * x
print(square(6))
10. Function with type hints
10. Function with type hints
python
# Example 10: Type hints
def multiply(x: int, y: int) -> int:
return x * y
print(multiply(4, 5))
# Example 10: Type hints
def multiply(x: int, y: int) -> int:
return x * y
print(multiply(4, 5))
11. Function to check even or odd
11. Function to check even or odd
python
# Example 11: Check even or odd
def check_even_odd(num):
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
check_even_odd(7)
# Example 11: Check even or odd
def check_even_odd(num):
if num % 2 == 0:
print(f"{num} is even")
else:
print(f"{num} is odd")
check_even_odd(7)
12. Function to reverse a string
12. Function to reverse a string
python
# Example 12: Reverse a string
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
# Example 12: Reverse a string
def reverse_string(s):
return s[::-1]
print(reverse_string("hello"))
13. Function to calculate average of a list
13. Function to calculate average of a list
python
# Example 13: Average of numbers
def average(numbers):
return sum(numbers) / len(numbers)
print(average([10, 20, 30]))
# Example 13: Average of numbers
def average(numbers):
return sum(numbers) / len(numbers)
print(average([10, 20, 30]))
14. Function with nested function
14. Function with nested function
python
# Example 14: Nested function
def outer():
def inner():
print("Hello from inner function")
inner()
outer()
# Example 14: Nested function
def outer():
def inner():
print("Hello from inner function")
inner()
outer()
15. Global vs local variable
15. Global vs local variable
python
# Example 15: Scope example
x = 10
def change():
x = 5 # local variable
print("Inside function:", x)
change()
print("Outside function:", x)
# Example 15: Scope example
x = 10
def change():
x = 5 # local variable
print("Inside function:", x)
change()
print("Outside function:", x)
16. Function to check prime number
16. Function to check prime number
python
# Example 16: Prime check
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(11))
# Example 16: Prime check
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return False
return True
print(is_prime(11))
17. Function to count vowels in a string
17. Function to count vowels in a string
python
# Example 17: Count vowels
def count_vowels(s):
vowels = "aeiou"
return sum(1 for char in s.lower() if char in vowels)
print(count_vowels("Python"))
# Example 17: Count vowels
def count_vowels(s):
vowels = "aeiou"
return sum(1 for char in s.lower() if char in vowels)
print(count_vowels("Python"))
18. Function that returns multiple values
18. Function that returns multiple values
python
# Example 18: Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 8, 4])
print("Min:", low, "Max:", high)
# Example 18: Multiple return values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 8, 4])
print("Min:", low, "Max:", high)
19. Higher-order function (function as argument)
19. Higher-order function (function as argument)
python
# Example 19: Function as argument
def apply_twice(func, value):
return func(func(value))
def increment(x):
return x + 1
print(apply_twice(increment, 3))
# Example 19: Function as argument
def apply_twice(func, value):
return func(func(value))
def increment(x):
return x + 1
print(apply_twice(increment, 3))
20. Function with docstring
20. Function with docstring
python
# Example 20: Docstring
def square(n):
"""Return the square of a number."""
return n * n
print(square(6))
print(square.__doc__)
# Example 20: Docstring
def square(n):
"""Return the square of a number."""
return n * n
print(square(6))
print(square.__doc__)
21. Function to convert Celsius to Fahrenheit
21. Function to convert Celsius to Fahrenheit
python
# Example 21: Celsius to Fahrenheit
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
print(celsius_to_fahrenheit(25))
# Example 21: Celsius to Fahrenheit
def celsius_to_fahrenheit(c):
return (c * 9/5) + 32
print(celsius_to_fahrenheit(25))
22. Function to find the longest word in a list
22. Function to find the longest word in a list
python
# Example 22: Longest word
def longest_word(words):
return max(words, key=len)
print(longest_word(["python", "java", "golang", "rust"]))
# Example 22: Longest word
def longest_word(words):
return max(words, key=len)
print(longest_word(["python", "java", "golang", "rust"]))
23. Function to check if a string is a palindrome
23. Function to check if a string is a palindrome
python
# Example 23: Palindrome check
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
# Example 23: Palindrome check
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
24. Function to get factorial using recursion
24. Function to get factorial using recursion
python
# Example 24: Recursive factorial
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
# Example 24: Recursive factorial
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
print(factorial(5))
25. Function to flatten a 2D list
25. Function to flatten a 2D list
python
# Example 25: Flatten list
def flatten(matrix):
return [item for row in matrix for item in row]
print(flatten([[1, 2], [3, 4], [5, 6]]))
# Example 25: Flatten list
def flatten(matrix):
return [item for row in matrix for item in row]
print(flatten([[1, 2], [3, 4], [5, 6]]))
26. Function to remove duplicates from a list
26. Function to remove duplicates from a list
python
# Example 26: Remove duplicates
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))
# Example 26: Remove duplicates
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 2, 3, 4, 4, 5]))
27. Function with try-except block
27. Function with try-except block
python
# Example 27: Try-except in function
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
print(divide(10, 0))
# Example 27: Try-except in function
def divide(a, b):
try:
return a / b
except ZeroDivisionError:
return "Cannot divide by zero"
print(divide(10, 0))
28. Function to capitalize each word
28. Function to capitalize each word
python
# Example 28: Capitalize words
def title_case(sentence):
return sentence.title()
print(title_case("hello world from python"))
# Example 28: Capitalize words
def title_case(sentence):
return sentence.title()
print(title_case("hello world from python"))
29. Function to count word frequency
29. Function to count word frequency
python
# Example 29: Word count
def word_count(text):
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
print(word_count("apple orange apple banana orange apple"))
# Example 29: Word count
def word_count(text):
words = text.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
return freq
print(word_count("apple orange apple banana orange apple"))
30. Function to generate Fibonacci sequence
30. Function to generate Fibonacci sequence
python
# Example 30: Fibonacci sequence
def fibonacci(n):
sequence = [0, 1]
for _ in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
print(fibonacci(10))
# Example 30: Fibonacci sequence
def fibonacci(n):
sequence = [0, 1]
for _ in range(2, n):
sequence.append(sequence[-1] + sequence[-2])
return sequence[:n]
print(fibonacci(10))
31. Function to check if a number is positive, negative or zero
31. Function to check if a number is positive, negative or zero
python
# Example 31: Number sign check
def check_number(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
print(check_number(-5))
# Example 31: Number sign check
def check_number(n):
if n > 0:
return "Positive"
elif n < 0:
return "Negative"
else:
return "Zero"
print(check_number(-5))
32. Function to count characters in a string
32. Function to count characters in a string
python
# Example 32: Character count
def char_count(s):
return {char: s.count(char) for char in set(s)}
print(char_count("hello"))
# Example 32: Character count
def char_count(s):
return {char: s.count(char) for char in set(s)}
print(char_count("hello"))
33. Function to check if a list is sorted
33. Function to check if a list is sorted
python
# Example 33: Sorted check
def is_sorted(lst):
return lst == sorted(lst)
print(is_sorted([1, 2, 3]))
print(is_sorted([3, 2, 1]))
# Example 33: Sorted check
def is_sorted(lst):
return lst == sorted(lst)
print(is_sorted([1, 2, 3]))
print(is_sorted([3, 2, 1]))
34. Function to find common elements in two lists
34. Function to find common elements in two lists
python
# Example 34: Common elements
def common_elements(a, b):
return list(set(a) & set(b))
print(common_elements([1, 2, 3], [2, 3, 4]))
# Example 34: Common elements
def common_elements(a, b):
return list(set(a) & set(b))
print(common_elements([1, 2, 3], [2, 3, 4]))
35. Function to repeat a string multiple times
35. Function to repeat a string multiple times
python
# Example 35: Repeat string
def repeat_string(s, n):
return s * n
print(repeat_string("ha", 3))
# Example 35: Repeat string
def repeat_string(s, n):
return s * n
print(repeat_string("ha", 3))
36. Function to convert a list of strings to uppercase
36. Function to convert a list of strings to uppercase
python
# Example 36: Uppercase list
def to_uppercase(words):
return [word.upper() for word in words]
print(to_uppercase(["python", "code", "fun"]))
# Example 36: Uppercase list
def to_uppercase(words):
return [word.upper() for word in words]
print(to_uppercase(["python", "code", "fun"]))
37. Function to get the second largest number in a list
37. Function to get the second largest number in a list
python
# Example 37: Second largest
def second_largest(numbers):
unique = list(set(numbers))
unique.sort()
return unique[-2] if len(unique) >= 2 else None
print(second_largest([10, 20, 30, 30]))
# Example 37: Second largest
def second_largest(numbers):
unique = list(set(numbers))
unique.sort()
return unique[-2] if len(unique) >= 2 else None
print(second_largest([10, 20, 30, 30]))
38. Function to format full name
38. Function to format full name
python
# Example 38: Format name
def format_name(first, last):
return f"{first.strip().title()} {last.strip().title()}"
print(format_name(" john", "DOE "))
# Example 38: Format name
def format_name(first, last):
return f"{first.strip().title()} {last.strip().title()}"
print(format_name(" john", "DOE "))
39. Function to calculate the area of a circle
39. Function to calculate the area of a circle
python
# Example 39: Circle area
import math
def circle_area(radius):
return math.pi * radius ** 2
print(circle_area(3))
# Example 39: Circle area
import math
def circle_area(radius):
return math.pi * radius ** 2
print(circle_area(3))
40. Function to filter even numbers from a list
40. Function to filter even numbers from a list
python
# Example 40: Filter even numbers
def filter_even(nums):
return [n for n in nums if n % 2 == 0]
print(filter_even([1, 2, 3, 4, 5, 6]))
# Example 40: Filter even numbers
def filter_even(nums):
return [n for n in nums if n % 2 == 0]
print(filter_even([1, 2, 3, 4, 5, 6]))
What’s Next?
Awesome work learning how Python functions work! Now that you understand the basics, it's time to take your skills to the next level with powerful tools like iterators, generators, closures, and decorators. These concepts will help you write more efficient, flexible, and Pythonic code.