Class 4
Class 4
Defining a Function
To define a function, use the def keyword followed by the function name and
parentheses () which may include parameters.
The function body starts with a colon : and is indented.
Syntax
def function_name(parameters):
"""
Docstring: Description of the function.
"""
# Function body
statement(s)
return value # Optional
Calling a Function
To call a function, use the function name followed by parentheses containing
arguments.
In [2]: greet("Alice")
Hello, Alice!
In [3]: greet('jon')
Hello, jon!
Function Parameters
Functions can accept parameters to make them more flexible.
1. Positional Parameters
Parameters are passed in the order they are defined.
1/6
result = add(3, 5)
print(result)
In [5]: add(5,8)
13
Out[5]:
2. Default Parameters
You can provide default values for parameters.
In [7]: greet("jon")
Hello, jon!
jon Hello
3. Keyword Arguments
You can pass arguments using the parameter names, allowing you to skip or rearrange them.
In [10]: describe_pet("Buddy")
4. Variable-Length Arguments
*args (Non-Keyword Arguments)
Allows you to pass a variable number of non-keyword arguments to a function.
10
15
2/6
print(f"{key}: {value}")
name: Alice
age: 30
city: New York
Returning Values
Functions can return values using the return statement. If no return statement is used,
the function returns None by default.
result = square(4)
print(result)
16
Lambda Functions
Lambda functions are small anonymous functions defined using the lambda keyword. They
can have any number of arguments but only one expression.
25
Local Scope: Variables declared inside a function are local to that function.
Global Scope: Variables declared outside any function are global and can be accessed
anywhere in the code.
def my_fun():
x =50 # Local variable
3/6
print(x)
def my_fun1():
x =60 # Local variable
print(x)
def my_fun2():
print(x)
In [22]: my_fun()
50
In [23]: my_fun1()
60
In [24]: print(x)
100
In [25]: my_fun2()
100
In [26]: x = 300
def myfunc():
global x
x = 400
In [27]: print(x)
300
In [28]: myfunc()
In [29]: print(x)
400
In [30]: print(x)
400
Recursion in Python
Recursion is a programming technique where a function calls itself to solve smaller
instances of the same problem.
This approach can simplify the solution for problems that exhibit self-similarity and can
be broken down into simpler sub-problems.
4/6
Detailed Examples
Example 1: Factorial Calculation
The factorial of a non-negative integer ( n ) is the product of all positive integers less than or
equal to ( n ). The factorial of ( n ) is denoted as ( n! ). For example:
print(factorial(5))
print(factorial(0))
print(factorial(3))
120
1
6
In this function:
When n is 0 or 1, it returns 1.
Otherwise, it calls itself with n-1 and multiplies the result by n .
5/6
print(fibonacci(5))
print(fibonacci(6))
5
8
6/6