Table of contents

Functions

Functions are a core concept in programming that allow you to organize your code into reusable blocks. They enable you to break down complex problems into smaller, manageable pieces and promote code reuse. In this comprehensive guide, we’ll explore the fundamentals of functions in Python, including their syntax, usage, and practical examples.

A function is a block of organized, reusable code that performs a single, related action. Functions provide better modularity for your application and a high degree of code reusability.

Example

def greet(): print("Hello, World!")

In this example, greet is a simple function that prints a greeting message.

Functions in Python are defined using the def keyword, followed by the function name and parentheses ().

Syntax

def function_name(parameters): # code to execute return result

Example

def greet(name): print(f"Hello, {name}!")

This function takes a parameter name and prints a personalized greeting.

Once a function is defined, you can call it by using its name followed by parentheses ().

Example

greet("Alice") # Output: Hello, Alice! greet("Bob") # Output: Hello, Bob!

Functions can take multiple parameters, which are specified within the parentheses during the function definition.

Example

def add(a, b): return a + b result = add(3, 5) print(result) # Output: 8

Default Parameters

You can define default values for parameters. If no argument is provided, the default value is used.

def greet(name="World"): print(f"Hello, {name}!") greet() # Output: Hello, World! greet("Alice") # Output: Hello, Alice!

Keyword Arguments

You can pass arguments by their parameter name, allowing you to specify values out of order.

def describe_person(name, age): print(f"{name} is {age} years old.") describe_person(age=25, name="Alice") # Output: Alice is 25 years old.

Variable-Length Arguments

You can define functions that accept any number of arguments using *args for non-keyword arguments and **kwargs for keyword arguments.

def add(*args): return sum(args) print(add(1, 2, 3)) # Output: 6 print(add(4, 5, 6, 7, 8)) # Output: 30 def describe_person(**kwargs): for key, value in kwargs.items(): print(f"{key}: {value}") describe_person(name="Alice", age=25, city="Wonderland") # Output: # name: Alice # age: 25 # city: Wonderland

Functions can return a value using the return statement.

Example

def multiply(a, b): return a * b result = multiply(4, 5) print(result) # Output: 20

Variables defined inside a function are local to that function and cannot be accessed outside of it. The scope of a variable is the region of the program where the variable is recognized.

Example

def my_function(): x = 10 # local variable print(x) my_function() # Output: 10 # print(x) # Error: NameError: name 'x' is not defined

You can define functions inside other functions. These are called nested functions.

Example

def outer_function(): def inner_function(): print("Hello from the inner function!") inner_function() outer_function()

Lambda functions are small anonymous functions defined using the lambda keyword. They can have any number of arguments but only one expression.

Syntax

lambda arguments: expression

Example

add = lambda a, b: a + b print(add(3, 5)) # Output: 8 # Lambda function inside another function def my_function(n): return lambda x: x * n doubler = my_function(2) print(doubler(5)) # Output: 10

Write a function to convert temperatures between Fahrenheit and Celsius.

def celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32 def fahrenheit_to_celsius(fahrenheit): return (fahrenheit - 32) * 5/9 temp_c = 100 temp_f = celsius_to_fahrenheit(temp_c) print(f"{temp_c}°C is {temp_f}°F") temp_f = 212 temp_c = fahrenheit_to_celsius(temp_f) print(f"{temp_f}°F is {temp_c}°C")

Write a simple calculator that can add, subtract, multiply, and divide two numbers.

def add(a, b): return a + b def subtract(a, b): return a - b def multiply(a, b): return a * b def divide(a, b): if b != 0: return a / b else: return "Error: Division by zero" print("Select operation:") print("1. Add") print("2. Subtract") print("3. Multiply") print("4. Divide") choice = input("Enter choice (1/2/3/4): ") num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) if choice == '1': print(f"{num1} + {num2} = {add(num1, num2)}") elif choice == '2': print(f"{num1} - {num2} = {subtract(num1, num2)}") elif choice == '3': print(f"{num1} * {num2} = {multiply(num1, num2)}") elif choice == '4': print(f"{num1} / {num2} = {divide(num1, num2)}") else: print("Invalid input")

Write a function that checks if a given string is a palindrome (reads the same forward and backward).

def is_palindrome(s): return s == s[::-1] word = input("Enter a word: ") if is_palindrome(word): print(f"{word} is a palindrome.") else: print(f"{word} is not a palindrome.")

Write a function to generate the Fibonacci sequence up to n terms.

def fibonacci(n): sequence = [] a, b = 0, 1 while len(sequence) < n: sequence.append(a) a, b = b, a + b return sequence terms = int(input("Enter the number of terms: ")) print(f"Fibonacci sequence: {fibonacci(terms)}")

In this guide, we’ve explored the fundamentals of functions in Python, including their definition, parameters, return values, scope, nested functions, and lambda functions. Functions are essential for writing modular and reusable code, making your programs more organized and easier to maintain. Practice these concepts with the provided examples and exercises to enhance your understanding and programming skills. In the next section, we will delve into data structures, which help you organize and manage data efficiently. Happy coding!