Functions in Python
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 + "!")
greet("Alice") # Output: Hello, Alice!
Return Values:
Functions can return values using the return statement:
Python
def square(x):
return x * x
result = square(5)
print(result) # Output: 25
Function Arguments:
Python supports various ways to pass arguments to functions:
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"
area1 = calculate_area(5, 4) # Positional arguments
area2 = calculate_area(width=3, length=6) # Keyword arguments
area3 = calculate_area(5, shape="square") # Default and positional
arguments
print(area1, area2, area3)
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.
Built-in Functions in Python
Python comes with a rich set of built-in functions that you can use to perform various tasks
without having to write your own code. Here are some of the most commonly used ones:
Basic Functions:
abs(x): Returns the absolute value of a number.
divmod(a, b): Returns a tuple containing the quotient and remainder of integer
division.
max(iterable, *args): Returns the largest item in an iterable or the largest of two
or more arguments.
min(iterable, *args): Returns the smallest item in an iterable or the smallest of
two or more arguments.
pow(base, exp[, mod]): Returns the value of base to the power of exp.
round(number[, ndigits]): Rounds a number to a specified number of decimal
places.
sum(iterable, start=0): Returns the sum of items in an iterable.
Type Conversion Functions:
int(x): Converts a number or string to an integer.
float(x): Converts a number or string to a floating-point number.
str(x): Converts an object to a string representation.
bool(x): Converts an object to a Boolean value.
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:
math.sqrt(x): Returns the square root of a number.
math.pi: Returns the value of pi.
math.e: Returns the value of Euler's number.
math.sin(x), math.cos(x), math.tan(x): Trigonometric functions.
String Manipulation Functions:
len(s): Returns the length of a string.
str.upper(), str.lower(), str.capitalize(): Case conversion functions.
str.strip(), str.lstrip(), str.rstrip(): Removes whitespace from strings.
str.split(sep=None): Splits a string into a list of substrings.
str.join(iterable): Joins elements of an iterable into a string.
List and Tuple Functions:
len(list): Returns the length of a list or tuple.
list.append(x): Adds an element to the end of a list.
list.insert(i, x): Inserts an element at a specific index in a list.
list.remove(x): Removes the first occurrence of an element from a list.
tuple(iterable): Converts an iterable to a tuple.
Date and Time Functions in Python
Python offers a robust module named datetime to handle date and time operations
effectively. Here are some common functions and methods within this module:
Importing the datetime Module:
Python
import datetime
Getting Current Date and Time:
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
print(year, month, day, hour, minute, second, microsecond)
Creating Date and Time Objects:
Python
# Create a specific date
date_of_birth = datetime.date(1995, 12, 25)
print(date_of_birth)
# Create a specific time
time_of_meeting = datetime.time(10, 30, 30)
print(time_of_meeting)
# Create a specific datetime
datetime_obj = datetime.datetime(2023, 11, 18, 16, 33, 22)
print(datetime_obj)
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
Formatting Date and Time:
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:
Use datetime.timedelta to represent time differences.
Utilize datetime.datetime.strptime() to parse strings into datetime objects.
Explore the pytz module for handling time zones.
Consider using libraries like dateutil for advanced date and time manipulation.
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):
Generates a random float number between a (inclusive) and b (inclusive).
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):
Generates a random integer number between a (inclusive) and b (inclusive).
Python
random_integer = random.randint(1, 10)
print(random_integer) # Output: A random integer between 1 and 10
4. random.randrange(start, stop[, step]):
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):
Chooses a random element from a sequence (like a list or tuple).
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
Global and Local Variables in Python
In Python, variables declared inside a function are local to that function, while variables
declared outside a function are global.
Local Variables:
Scope: Limited to the function where they are declared.
Lifetime: Exists only during the function's execution.
Python
def my_function():
x = 10 # Local variable
print(x)
my_function() # Output: 10
Global Variables:
Scope: Accessible from anywhere in the program.
Lifetime: Exists throughout the program's execution.
Python
x = 20 # Global variable
def my_function():
print(x)
my_function() # Output: 20
Modifying Global Variables Inside Functions:
To modify a global variable inside a function, you need to declare it as global:
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.
Basic Structure of a Recursive Function:
Python
def recursive_function(input):
# Base case: If the input is simple enough, return a result directly
if base_condition(input):
return base_result
# Recursive case: Break down the problem into smaller subproblems
smaller_input = reduce_input(input)
result = recursive_function(smaller_input)
# Combine the results of the subproblems
return combine_results(result, input)
Example: Factorial Calculation
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