Python Module 3
Python Module 3
In Python, functions are blocks of reusable code that perform specific tasks. They enhance
code readability, modularity, and reusability.
Defining a Function:
To define a function, you use the def keyword followed by the function name and
parentheses:
Python
def function_name():
# Function body
Function Parameters:
You can pass values to a function through parameters. These parameters act as variables
within the function's scope:
Python
def greet(name):
print("Hello, " + name + "!")
Return Values:
Python
def square(x):
return x * x
result = square(5)
print(result) # Output: 25
Function Arguments:
1. Positional Arguments:
o Arguments are assigned to parameters based on their position.
2. Keyword Arguments:
o Arguments are assigned to parameters by keyword, regardless of their
position.
3. Default Arguments:
o Parameters can have default values assigned to them.
4. Variable-Length Arguments:
o You can use *args to accept an arbitrary number of positional arguments and
**kwargs to accept an arbitrary number of keyword arguments.
Example:
Python
def calculate_area(length, width, shape="rectangle"):
if shape == "rectangle":
return length * width
elif shape == "square":
return length * length
else:
return "Invalid shape"
Key Points:
Functions can be defined anywhere in your code, but they are typically defined at the
beginning of a module or script.
Functions can be called from other functions.
Functions can be recursive, meaning they can call themselves.
Functions can be used to organize your code into smaller, more manageable pieces.
Functions can be used to create libraries of reusable code.
Basic Functions:
Input/Output Functions:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
Prints objects to the console.
input(prompt=''): Reads a line from input, converts it to a string, and returns it.
Mathematical Functions:
Python offers a robust module named datetime to handle date and time operations
effectively. Here are some common functions and methods within this module:
Python
import datetime
Python
# Get current date and time
now = datetime.datetime.now()
print(now) # Output: 2023-11-18 16:33:22.234123
Extracting Components:
Python
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
microsecond = now.microsecond
Python
# Create a specific date
date_of_birth = datetime.date(1995, 12, 25)
print(date_of_birth)
Timedeltas:
Python
# Calculate time difference
t1 = datetime.datetime(2023, 11, 18, 12, 00)
t2 = datetime.datetime(2023, 11, 18, 18, 00)
time_difference = t2 - t1
print(time_difference) # Output: 6:00:00
Python
formatted_date = now.strftime("%d/%m/%Y") # 18/11/2023
formatted_time = now.strftime("%H:%M:%S") # 16:33:22
formatted_datetime = now.strftime("%d/%m/%Y %H:%M:%S") # 18/11/2023
16:33:22
print(formatted_date, formatted_time, formatted_datetime)
Additional Tips:
By effectively using the datetime module, you can perform a wide range of date and time
operations in your Python programs.
Generating Random Numbers in Python
Python provides a built-in module named random to generate random numbers. Here are
some common functions:
1. random.random():
Generates a random float number between 0.0 (inclusive) and 1.0 (exclusive).
Python
import random
random_float = random.random()
print(random_float) # Output: A random float between 0.0 and 1.0
2. random.uniform(a, b):
Python
random_float = random.uniform(10, 20)
print(random_float) # Output: A random float between 10.0 and 20.0
3. random.randint(a, b):
Python
random_integer = random.randint(1, 10)
print(random_integer) # Output: A random integer between 1 and 10
Generates a random integer from the range start to stop with the specified step.
Python
random_integer = random.randrange(0, 101, 5) # Random integer from 0, 5,
10, ..., 100
print(random_integer)
5. random.choice(sequence):
Python
my_list = [1, 2, 3, 4, 5]
random_choice = random.choice(my_list)
print(random_choice) # Output: A random element from the list
6. random.shuffle(sequence):
Shuffles the elements of a sequence in place.
Python
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(my_list) # Output: A shuffled list
In Python, variables declared inside a function are local to that function, while variables
declared outside a function are global.
Local Variables:
Python
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
Global Variables:
Python
x = 20 # Global variable
def my_function():
print(x)
my_function() # Output: 20
Python
x = 10
def modify_global():
global x
x = 20
modify_global()
print(x) # Output: 20
Best Practices:
Minimize Global Variables: Excessive use of global variables can make code harder
to understand and maintain.
Use Function Arguments and Return Values: Pass necessary data to functions as
arguments and return results.
Consider Using Classes: For complex scenarios, encapsulate related variables and
functions within a class.
Recursion in Python
Recursion is a programming technique where a function calls itself directly or indirectly. It's
often used to solve problems that can be broken down into smaller, self-similar
subproblems.
Python
def recursive_function(input):
# Base case: If the input is simple enough, return a result directly
if base_condition(input):
return base_result
Python
def factorial(n):
if n == 0:
return 1 # Base case
else:
return n * factorial(n - 1) # Recursive case
result = factorial(5)
print(result) # Output:
120