Functions
What Are Functions?
- Functions are blocks of code that perform specific tasks. They can take inputs (arguments) and return outputs.
Why Use Functions?
- They help organize code, making it reusable and easier to understand.
Basic Function Syntax:
Defining a function:
pythondef function_name(parameters): # code to execute return value
Examples and Exercises:
- Introduction to Functions:
How to define and call a function:
pythondef greet(name): return (('Hello, ' + name) + "!") print(greet("Alice"))- Output:
Hello, Alice!
- Output:
- Passing Multiple Arguments (
*args): - Keyword Arguments (
**kwargs): - Returning Values from a Function:
Using the
returnstatement:pythondef square(x): return x * x print(square(4))- Output:
16
- Output:
- Returning a Function from Another Function:
Higher-order functions:
pythondef outer_function(msg): def inner_function(): return msg return inner_function my_function = outer_function("Hello") print(my_function())- Output:
Hello
- Output:
- Recursive Functions:
Functions that call themselves:
pythondef factorial(n): if n == 1: return 1 else: return n * factorial(n - 1) print(factorial(5))- Output:
120
- Output:
Summary:
- Functions are essential in Python for organizing and reusing code. Understanding how to define, call, and use various types of functions will help you write more efficient and manageable programs. Practice these examples and exercises to become comfortable with functions!