CONTENT -Python Programming
CONTENT -Python Programming
Introduction to Python
1
2008: Python 3.0 launched, not fully backward compatible with Python 2.x,
focused on removing legacy issues.
2020: Official end of support for Python 2.x.
Present: Python continues to grow in popularity and is widely used in areas like
data science, AI, web development, and automation.
1.2 Features of Python:
Python is a powerful and versatile programming language known for its
simplicity and readability. It is easy to learn and use, making it an excellent choice
for both beginners and experienced developers. Since it is an interpreted language,
Python executes code line by line, which simplifies debugging and testing. Being a
high-level language, it handles complex programming details such as memory
management automatically.
Python uses dynamic typing, so you don’t need to declare the type of variables
explicitly. It supports multiple programming paradigms, including object-oriented,
procedural, and functional programming. One of Python’s strengths is its large
standard library, which provides tools and modules for a wide range of tasks,
including file handling, regular expressions, networking, and web services.
Python is cross-platform, meaning it can run on different operating systems like
Windows, macOS, and Linux without modification. Its vast ecosystem includes
thousands of third-party packages that extend its capabilities in areas like web
development, machine learning, data analysis, and automation. Python can also be
embedded in other languages like C or C++, making it highly extensible.
Additionally, it supports the development of graphical user interfaces through
libraries such as Tkinter and PyQt.
Thanks to its clear syntax and wide community support, Python is widely used for
rapid application development, scripting, and prototyping across many industries.
1.3 Applications of Python
Python is used in a wide range of applications across various industries due
to its simplicity, versatility, and extensive libraries. In web development, Python is
popular for building server-side applications using frameworks like Django and
Flask. In the field of data science and machine learning, Python is a dominant
language, supported by powerful libraries such as NumPy, Pandas, Matplotlib,
Scikit-learn, and TensorFlow. It is also widely used in automation and scripting to
2
write programs that automate repetitive tasks, such as file handling, web scraping,
and system administration. In software development, Python is often used for
creating desktop applications, games, and command-line tools. Additionally,
Python plays a significant role in the development of artificial intelligence and
deep learning systems. It is used in the scientific and academic community for
simulations, research, and data analysis. Python is also commonly used in the
finance industry for quantitative and algorithmic trading. Its role in embedded
systems, IoT projects, and network programming further highlights its flexibility
and growing relevance in modern technology
1.4 Installing Python and IDEs (IDLE, VS Code, PyCharm)
To start programming in Python, you need to install Python itself and
optionally choose an Integrated Development Environment (IDE) to write and run
your code more efficiently. Below is a guide on installing Python and popular
IDEs like IDLE, Visual Studio Code (VS Code), and PyCharm.
Installing Python
To install Python, follow these steps:
Go to the official Python website:
https://www.python.org/downloads/
Download the latest version suitable for your operating system (Windows, macOS,
or Linux).
Run the installer:
On Windows, make sure to check the box "Add Python to PATH" before clicking
"Install Now."
On macOS and Linux, you may need to use terminal commands if it’s not installed
by default.
After installation, open a terminal or command prompt and type:
To verify that Python is installed correctly.
IDLE (Integrated Development and Learning Environment)
IDLE comes installed with Python, so you don’t need to install it separately.
To open it:
3
On Windows, search for IDLE in the Start Menu.
On macOS/Linux, type idle or idle3 in the terminal.
IDLE is lightweight and suitable for beginners. It includes a simple code editor and
an interactive shell.
Installing Visual Studio Code (VS Code)
Download VS Code from:
https://code.visualstudio.com/
Install it like any regular application.
Install the Python extension:
Open VS Code.
Go to the Extensions panel (Ctrl+Shift+X or Cmd+Shift+X).
Search for "Python" and install the extension provided by Microsoft.
After setting up, you can create .py files and run them directly from VS Code.
Installing PyCharm
Download PyCharm from:
https://www.jetbrains.com/pycharm/download/
Choose between:
Community Edition (free and suitable for most users)
Professional Edition (paid, includes advanced features for web development,
database tools, etc.)
Install PyCharm and set the interpreter to the version of Python you installed.
PyCharm is a powerful IDE, especially useful for larger projects and professional
development.
1.5 Python syntax basics
Python syntax is designed to be simple and readable, making it easy for
beginners to learn and use. Here's a basic overview of Python syntax essentials:
1. Printing Output
4
To display something on the screen, use the print() function:
print("Hello, world!")
2. Variables and Data Types
You don’t need to declare variable types in Python:
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
3. Indentation
Python uses indentation (spaces or tabs) to define blocks of code instead of
braces {}:
if age > 18:
print("Adult")
else:
print("Minor")
4. Comments
Use # for single-line comments:
# This is a comment
Use triple quotes for multi-line comments or docstrings:
"""
This is a
multi-line comment
"""
5. Input from User
To take input from the user:
name = input("Enter your name: ")
5
print("Hello, " + name)
6. Control Structures
Conditional Statements:
if age >= 18:
print("You can vote.")
elif age == 17:
print("Almost there!")
else:
print("Too young to vote.")
Loops:
# For loop
for i in range(5):
print(i)
# While loop
count = 0
while count < 5:
print(count)
count += 1
7. Functions
Define and call functions using def:
def greet(name):
print("Hello, " + name)
greet("Alice")
8. Lists
Lists are ordered, mutable collections:
6
Chapter 2:
Variables, Data Types, and Operators
In Python, variables are used to store data, and they don't require
explicit declaration of their type, making Python a dynamically typed language. A
variable is created by simply assigning a value to a name using the assignment
operator =. For example, x = 10 creates a variable x and assigns it the integer value
of 10. Data types in Python include basic types like integers (int), floating-point
numbers (float), and strings (str). There are also boolean values (True or False),
lists, tuples, dictionaries, sets, and more complex types. Python automatically
determines the type of a variable based on the assigned value, which is why it's
referred to as dynamically typed. In addition to variables and data types, operators
in Python are used to perform operations on variables and values. These include
arithmetic operators like +, -, *, and / for performing mathematical calculations.
Python also supports comparison operators like ==, !=, <, >, and logical operators
like and, or, and not. These operators are essential for controlling the flow of
programs through conditional statements and loops. Understanding how to use
variables, data types, and operators effectively forms the foundation of
programming in Python, allowing developers to manipulate data and create more
complex functionalities.
2.1 Variables and Constants
In Python, variables are used to store data that can be changed during the
execution of a program. A variable is essentially a name that refers to a value in
memory, and it is created by assigning a value to a name using the assignment
operator =. For example, age = 25 creates a variable age and assigns it the value
25. The value of a variable can be modified during runtime. Python is a
dynamically typed language, meaning that variables do not need to be explicitly
declared with a type—Python automatically determines the type based on the
assigned value.
On the other hand, constants are values that are meant to remain unchanged
throughout the execution of a program. While Python does not have built-in
constant types, it is a common convention to use uppercase letters for constants.
7
For example, PI = 3.14159 is a constant in Python, and by convention, it should not
be modified during the program's execution. Although Python does not enforce
immutability of constants, developers rely on this naming convention to signal that
the value should remain constant.
Both variables and constants are fundamental in programming as they store data,
but the key difference lies in whether the data is intended to change or stay the
same throughout the program.
2.2 Data Types: int, float, str, bool, list, tuple, dict, set
In Python, data types define the kind of value a variable can hold. Understanding
these basic data types is crucial for writing effective Python programs. Here's a
look at the most commonly used ones:
1. int (Integer)
An int is a whole number, either positive or negative, without any decimal points.
It is used to represent values like counts, ages, or quantities.
Example:
age = 25
2. float (Floating-point number)
A float is a number that has a decimal point. It’s used to represent real numbers or
numbers that require precision, such as measurements, currency, or scientific data.
Example:
price = 19.99
3. str (String)
A str is used to represent text. A string can contain letters, numbers, symbols, or
spaces and is enclosed in either single quotes (') or double quotes (").
Example:
name = "Alice"
4. bool (Boolean)
8
A bool represents one of two possible values: True or False. It is often used in
conditional statements to evaluate expressions or conditions.
Example:
is_student = True
5. list
A list is a collection of ordered, mutable items. Lists can store different data types
in a single collection, and their elements are indexed. You can modify a list after it
is created
fruits = ["apple", "banana", "cherry"]
6. tuple
A tuple is similar to a list, but it is immutable (cannot be changed after creation).
Tuples are often used for fixed collections of items. They are defined by enclosing
items in parentheses (()).
Example:
coordinates = (10.5, 20.7)
7. dict (Dictionary)
A dict is an unordered collection of key-value pairs. Each item in a dictionary is
accessed via its key rather than an index. Keys must be unique, while values can be
of any data type.
Example:
person = {"name": "John", "age": 30}
8. set
A set is an unordered collection of unique items. It is useful when you need to store
values without duplicates and perform set operations like unions and intersections.
Example:
colors = {"red", "green", "blue"}
2.3 Type Conversion
9
In Python, type conversion refers to the process of converting one data type into
another. This is essential when performing operations between different types or
when specific types are required by certain functions or methods. Python provides
several ways to perform type conversion, which can be broadly classified into
implicit and explicit conversion.
2.3.1 Implicit Type Conversion (Automatic)
Python automatically converts one data type to another when it is required, which
is known as implicit type conversion or type coercion. This happens when you mix
different types in an operation, and Python implicitly converts the data types to a
compatible type.
For example:
x = 10 # int
y = 3.14 # float
result = x + y # Python automatically converts x to float
print(result) # Output: 13.14
Here, x (an integer) is automatically converted to a float during the addition
operation.
2.3.2 Explicit Type Conversion (Manual)
Explicit type conversion is when you manually convert one data type to another
using built-in functions. This is often necessary when you need to ensure a specific
type for a variable, especially when working with user input or when you want to
perform operations that require matching types.
Python provides several built-in functions to convert between types:
int() – Converts a value to an integer
x = "42"
y = int(x) # Converts string to integer
print(y) # Output: 42
float() – Converts a value to a float
x = "3.14"
10
y = float(x) # Converts string to float
print(y) # Output: 3.14
str() – Converts a value to a string
x = 123
y = str(x) # Converts integer to string
print(y) # Output: "123"
bool() – Converts a value to a boolean
x=0
y = bool(x) # Converts integer to boolean (0 is False, any non-zero number is
True)
print(y) # Output: False
list() – Converts an iterable (like a tuple or string) to a list
x = (1, 2, 3)
y = list(x) # Converts tuple to list
print(y) # Output: [1, 2, 3]
tuple() – Converts an iterable to a tuple
x = [1, 2, 3]
y = tuple(x) # Converts list to tuple
print(y) # Output: (1, 2, 3)
set() – Converts an iterable to a set
x = [1, 2, 2, 3]
y = set(x) # Converts list to set (removes duplicates)
print(y) # Output: {1, 2, 3}
dict() – Converts a list of tuples into a dictionary
x = [("name", "Alice"), ("age", 25)]
y = dict(x) # Converts list of tuples to a dictionary
11
print(y) # Output: {'name': 'Alice', 'age': 25}
12
1. Arithmetic Operators
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication, division, and more.
+ : Addition (adds two values)
x = 10 + 5 # x = 15
- : Subtraction (subtracts the second value from the first)
x = 10 - 5 # x = 5
* : Multiplication (multiplies two values)
x = 10 * 5 # x = 50
/ : Division (divides the first value by the second, returns float)
x = 10 / 3 # x = 3.3333...
// : Floor Division (divides and returns the integer part of the quotient)
x = 10 // 3 # x = 3
% : Modulus (returns the remainder of the division)
x = 10 % 3 # x = 1
** : Exponentiation (raises the first number to the power of the second)
x = 2 ** 3 # x = 8
2. Comparison Operators
Comparison operators are used to compare two values and return a boolean
(True or False) based on the result of the comparison.
== : Equal to (checks if two values are equal)
5 == 5 # True
!= : Not equal to (checks if two values are not equal)
5 != 3 # True
13
> : Greater than (checks if the left value is greater than the right)
5 > 3 # True
< : Less than (checks if the left value is less than the right)
5 < 10 # True
>= : Greater than or equal to (checks if the left value is greater than or equal to the
right)
5 >= 5 # True
<= : Less than or equal to (checks if the left value is less than or equal to the right)
5 <= 10 # True
3. Logical Operators
Logical operators are used to combine conditional statements. They help in
determining the truth value of combined conditions.
and : Logical AND (returns True if both conditions are True)
x = (5 > 3) and (10 > 5) # True
or : Logical OR (returns True if at least one condition is True)
x = (5 > 3) or (10 < 5) # True
not : Logical NOT (reverses the logical state of its operand)
x = not(5 > 3) # False
4. Assignment Operators
Assignment operators are used to assign values to variables, and some of them
perform an operation while assigning the result.
= : Simple assignment (assigns a value to a variable)
x = 5 # x gets the value 5
+= : Add and assign (adds the right operand to the left operand and assigns the
result)
x=5
x += 3 # x becomes 8
14
-= : Subtract and assign (subtracts the right operand from the left operand and
assigns the result)
x=5
x -= 3 # x becomes 2
*= : Multiply and assign (multiplies the left operand by the right operand and
assigns the result)
x=5
x *= 3 # x becomes 15
/= : Divide and assign (divides the left operand by the right operand and assigns the
result)
x = 10
x /= 2 # x becomes 5.0
//= : Floor divide and assign (performs floor division and assigns the result)
x = 10
x //= 3 # x becomes 3
%= : Modulus and assign (performs modulus and assigns the result)
x = 10
x %= 3 # x becomes 1
**= : Exponentiation and assign (performs exponentiation and assigns the result)
x=2
x **= 3 # x becomes 8
5. Bitwise Operators
Bitwise operators are used to perform bit-level operations on binary numbers.
They are useful when you need to manipulate individual bits of data.
& : Bitwise AND (returns 1 if both bits are 1, otherwise 0)
5 & 3 # Result: 1 (binary: 0101 & 0011 = 0001)
| : Bitwise OR (returns 1 if at least one of the bits is 1)
15
5 | 3 # Result: 7 (binary: 0101 | 0011 = 0111)
^ : Bitwise XOR (returns 1 if only one of the bits is 1, but not both)
5 ^ 3 # Result: 6 (binary: 0101 ^ 0011 = 0110)
~ : Bitwise NOT (inverts the bits)
~5 # Result: -6 (binary: ~0101 = 1010 in two's complement)
<< : Left shift (shifts the bits of the number to the left by the specified number of
positions)
5 << 1 # Result: 10 (binary: 0101 << 1 = 1010)
>> : Right shift (shifts the bits of the number to the right by the specified number
of positions)
5 >> 1 # Result: 2 (binary: 0101 >> 1 = 0010)
Bitwise XOR (returns 1 if only one of the bits is 1, but not both)
5 ^ 3 # Result: 6 (binary: 0101 ^ 0011 = 0110)
~ : Bitwise NOT (inverts the bits)
~5 # Result: -6 (binary: ~0101 = 1010 in two's complement)
<< : Left shift (shifts the bits of the number to the left by the specified number of
positions)
5 << 1 # Result: 10 (binary: 0101 << 1 = 1010)
>> : Right shift (shifts the bits of the number to the right by the specified number
of positions)
5 >> 1 # Result: 2 (binary: 0101 >> 1 = 0010)
16
Chapter 3:
Control Flow
Control flow in Python refers to the order in which individual statements,
instructions, or function calls are executed or evaluated. Python provides several
tools to control the flow of a program, allowing developers to make decisions,
repeat tasks, and branch off in different directions based on conditions. The
primary control flow statements in Python include conditional statements, loops,
and loop control statements.
The most basic form of control flow is the conditional statement, using if, elif, and
else. These allow the program to make decisions and execute different blocks of
code depending on whether certain conditions are true. For example, an if
statement checks a condition, and if it's true, the corresponding block is executed.
If it’s false, the program can check other conditions using elif (else if) or fall back
to a default case using else.
Another essential part of control flow is loops, which are used to execute a block
of code multiple times. Python supports two types of loops: for loops and while
loops. A for loop is used to iterate over a sequence like a list, tuple, or string, and it
executes the block for each item in the sequence. A while loop, on the other hand,
continues to run as long as a specified condition remains true. Both loops are
commonly used for tasks such as processing items, repeating calculations, or
collecting data.
Python also provides loop control statements such as break, continue, and pass to
manage loop behavior more precisely. The break statement is used to exit the loop
prematurely, while continue skips the current iteration and moves to the next one.
The pass statement acts as a placeholder when no action is required.
Together, these control flow elements allow Python programs to make decisions
and repeat actions, forming the logical backbone of most software. Mastery of
control flow is essential for writing clear, efficient, and flexible code.
3.1 if, elif, else
In Python, if, elif, and else are conditional statements used to make decisions based
on certain conditions. These statements allow a program to execute different
blocks of code depending on whether a condition is true or false.
17
if Statement
The if statement is used to test a condition. If the condition is true, the block of
code under the if statement is executed.
x = 10
if x > 5:
print("x is greater than 5")
In this example, since x is greater than 5, the message will be printed.
elif Statement (short for else if)
The elif statement checks another condition if the previous if condition was false.
You can have multiple elif blocks in a chain.
x = 10
if x > 15:
print("x is greater than 15")
elif x == 10:
print("x is equal to 10")
Here, the first condition is false, but the elif condition is true, so the second
message is printed.
else Statement
The else statement runs if none of the if or elif conditions are true. It does not take
a condition.
x=3
if x > 10:
print("x is greater than 10")
elif x == 5:
print("x is equal to 5")
else:
print("x does not match any condition")
18
In this case, since both the if and elif conditions are false, the else block is
executed.
score = 75
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: F")
This code checks the value of score and prints the appropriate grade. It stops
checking as soon as one condition is True.
3.2 Nested conditions
Nested conditions refer to placing one if, elif, or else statement inside another if or
else block. This allows you to check multiple levels of conditions, meaning one
condition depends on the result of another.
Basic Syntax of Nested if
if condition1:
if condition2:
# Code block if both condition1 and condition2 are true
else:
# Code block if condition1 is true but condition2 is false
else:
# Code block if condition1 is false
Example 1: Checking Age and Citizenship
age = 20
19
citizen = True
if age >= 18:
if citizen:
print("You are eligible to vote.")
else:
print("You are old enough but not a citizen.")
else:
print("You are not old enough to vote.")
Explanation:
First, it checks if the person is 18 or older.
If true, it then checks if the person is a citizen.
If both are true, the person can vote; otherwise, it provides the appropriate
message.
Example 2: Nested with elif and else
score = 85
if score >= 60:
if score >= 90:
print("Excellent")
elif score >= 75:
print("Good")
else:
print("Passed")
else:
print("Failed")
Explanation:
The first if checks if the score is at least 60.
20
If true, it goes further to check specific ranges.
If not, the student fails.
3.3 while and for loops
Loops in Python: while and for loop
Loops in Python are used to execute a block of code repeatedly until a condition is
met or a sequence is fully processed. The two main types of loops in Python are
while loops and for loops.
while Loop
A while loop runs as long as a condition is true. It is typically used when the
number of iterations is not known in advance.
Syntax:
while condition:
# Code to execute repeatedly
Example:
count = 1
while count <= 5:
print("Count is:", count)
count += 1
Explanation:
The loop runs as long as count is less than or equal to 5. Each time, it prints the
current value and then increases it by 1.
for Loop
A for loop is used to iterate over a sequence (like a list, string, tuple, or range). It is
used when the number of iterations is known or defined.
Syntax:
for variable in sequence:
# Code to execute for each item in the sequence
21
Example:
for i in range(1, 6):
print("Number:", i)
Explanation:
This loop prints numbers from 1 to 5. range(1, 6) generates numbers starting from
1 up to (but not including) 6.
Loop Control Statements
break – Exits the loop early.
continue – Skips the current iteration and moves to the next.
pass – A placeholder that does nothing (used when a statement is syntactically
required).
Example with break and continue:
for i in range(1, 10):
if i == 5:
break # Stop the loop at 5
if i == 3:
continue # Skip 3
print(i)
3.4 break, continue, pass
Loop Control Statements in Python: break, continue, and pass
Python provides special statements that help control the behavior of loops. These
are break, continue, and pass. Each serves a specific purpose when managing how
and when loop iterations should execute or stop.
1. break Statement
The break statement is used to exit a loop prematurely, even if the loop condition is
still true or there are remaining items in the sequence.
Example:
22
for i in range(1, 10):
if i == 5:
break # Exit the loop when i is 5
print(i)
Output:
1
2
3
4
Explanation: The loop stops running when i equals 5.
2. continue Statement
The continue statement is used to skip the current iteration and move to the next
iteration of the loop.
Example:
for i in range(1, 6):
if i == 3:
continue # Skip when i is 3
print(i)
Output:
1
2
4
5
Explanation: When i is 3, the loop skips printing and moves to the next number.
23
3. pass Statement
The pass statement is a placeholder. It does nothing and is used when a statement
is syntactically required but you don’t want to perform any action.
Example:
for i in range(1, 6):
if i == 3:
pass # Do nothing, just a placeholder
print(i)
Output
1
2
3
4
5
Explanation: The loop runs normally. When i is 3, pass does nothing, and the loop
continues as usual.
3.5 Pattern Program
A pattern program in Python prints a specific visual structure using loops and
characters like *, numbers, or alphabets. These programs help build logical
thinking and loop control skills.
24
1. Right-Angled Triangle
n=5
for i in range(1, n+1):
print("*" * i)
Output:
*
**
***
****
*****
*****
****
***
**
*
25
3. Pyramid Pattern
n=5
for i in range(n):
print(" " * (n-i-1) + "*" * (2*i+1))
Output:
*
***
*****
*******
*********
4. Number Triangle
python
n=5
for i in range(1, n+1):
for j in range(1, i+1):
print(j, end=" ")
print()
26
Output:
1
12
123
1234
12345
n=4
for i in range(1, n+1):
print(str(i) * i)
Output:
1
22
333
4444
6. Alphabet Triangle
n=5
ch = 65 # ASCII of A
for i in range(n):
27
for j in range(i+1):
print(chr(ch), end=" ")
ch += 1
print()
Output:
mathematica
A
BB
CCC
DDDD
EEEEE
7. Hollow Square
n=5
for i in range(n):
for j in range(n):
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
28
Output:
markdown
*****
* *
* *
* *
*****
8. Diamond Pattern
n=5
for i in range(n):
print(" " * (n-i-1) + "*" * (2*i+1))
for i in range(n-2, -1, -1):
print(" " * (n-i-1) + "*" * (2*i+1))
Output:
*
***
*****
*******
*********
*******
*****
***
*
29
Tips for Pattern Problems
Rows vs Columns: Outer loop = rows, inner loop = columns.
Use range() smartly: Count up or down as needed.
ASCII values for alphabets: Use chr() and ord().
Spacing matters for triangle/pyramid shapes.
Try dry runs: Manually trace loop variables.
Explanation
Pattern programming in Python is a fundamental skill for beginners that focuses on
printing structured designs or shapes using loops. These patterns can include stars
(*), numbers, alphabets, or symbols, arranged in specific shapes such as triangles,
pyramids, squares, or diamonds.
Pattern programs help students understand the flow of loops, nested loops, and
output formatting. They are commonly used in interviews to test logic-building
capabilities.
Why Learn Pattern Programming?
Builds strong logical thinking and problem-solving skills.
Improves understanding of loop control and nested loops.
Helps in mastering print formatting in Python.
Frequently asked in coding interviews and competitive exams.
Tools Required
A basic Python environment like:
Python IDE (IDLE, PyCharm, VS Code)
Online compilers (Replit, Jupyter Notebook)
Basic knowledge of:
for and while loops
Conditional statements (if, else)
The print() function
30
Core Concepts
1. Loops
The for loop is widely used in pattern programming to iterate through rows and
columns.
Nested loops help in creating rows (outer loop) and columns (inner loop).
Example:
for i in range(5): # Outer loop for rows
for j in range(i+1): # Inner loop for columns
print("*", end=" ")
print() # Moves to next line
2. String Multiplication
Python allows multiplication of strings:
print("*" * 3) # Output: ***
This is useful for creating repeated patterns without inner loops.
3. ASCII Characters
For alphabet patterns:
print(chr(65)) # Output: A
Use ord() to convert characters to ASCII values and chr() to convert them back.
Types of Patterns
Star Patterns
Right-Angled Triangle
Inverted Triangle
Pyramid
Diamond
31
Chapter 4:
Functions and Modules
In Python, functions and modules are powerful tools that help organize
code, promote reusability, and make programs more manageable and readable.
This chapter explores how to define and use functions, pass data between them,
and how to structure programs using modules.
4.1 Defining and calling functions
Defining a Function
You define a function using the def keyword followed by the function name and
parentheses () that may include parameters. The function body is indented, and it
can contain any valid Python code.
Syntax:
def function_name(parameters):
# code block
return value # optional
Example: Function without Parameters
def greet():
print("Hello, welcome to Python!")
Calling a Function
Once a function is defined, you can call it by using its name followed by
parentheses.
Example:
greet() # Output: Hello, welcome to Python!
Function with Parameters
Functions can accept input values called parameters. You provide the actual values
(arguments) when calling the function.
32
Example:
def greet(name):
print("Hello,", name)
greet("Alice") # Output: Hello, Alice
greet("Bob") # Output: Hello, Bob
Function with Return Value
A function can return a result using the return statement. This allows the result to
be used elsewhere in the program.
Example:
def add(a, b):
return a + b
result = add(5, 3)
print("Sum is:", result) # Output: Sum is: 8
Function with Default Parameters
You can provide default values for parameters. If no value is provided during the
call, the default is used.
Example:
def greet(name="Guest"):
print("Hello,", name)
greet() # Output: Hello, Guest
greet("Sophia") # Output: Hello, Sophia
33
In Python, arguments are the values you pass into a function, and return values are
the outputs that a function can send back to the part of the program that called it.
These two features make functions flexible, reusable, and powerful.
Arguments
Arguments are actual values passed to a function's parameters when the function is
called. Python supports different types of arguments:
1. Positional Arguments
These are passed in the same order as the function's parameters.
def add(a, b):
print(a + b)
add(5, 3) # Output: 8
2. Keyword Arguments
You specify the parameter names when calling the function.
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(age=25, name="Alice")
3. Default Arguments
You can assign default values to parameters. If no value is passed, the default is
used.
def greet(name="Guest"):
print("Hello", name)
34
If you don’t know how many arguments you'll get, use *args (for positional) or
**kwargs (for keyword).
def add_all(*numbers):
total = sum(numbers)
print("Total:", total)
35
Unlike regular functions defined using def, a lambda function can take multiple
arguments but only contains a single expression. The result of the expression is
automatically returned. Lambda functions are ideal for simplifying code where full
function definitions would be unnecessarily verbose.
Example:
36
Data Science and Numerical Computing Libraries
In the field of data science and numerical computing, several Python libraries stand
out. NumPy is a foundational library for handling large, multi-dimensional arrays
and matrices, along with a vast collection of mathematical functions to operate on
these arrays. It provides fast and memory-efficient operations essential for
scientific computing. Pandas builds on NumPy and offers high-level data structures
like DataFrames, making it ideal for data cleaning, manipulation, and analysis. Its
intuitive syntax and rich feature set make tasks like handling missing data,
grouping, merging datasets, and time-series analysis straightforward. For
visualization, Matplotlib allows the creation of static, animated, and interactive
plots, while Seaborn builds on it to offer prettier, more informative statistical
graphics. These libraries form the backbone of any data science workflow in
Python.
37
Flask, in contrast, is a lightweight and flexible web framework that provides the
bare essentials, making it ideal for microservices and smaller web apps. In the area
of automation and scripting, Selenium allows Python scripts to control web
browsers automatically, which is widely used in automated testing and web
scraping. BeautifulSoup is another popular library used for parsing HTML and
XML documents, enabling developers to extract data from web pages with ease.
These libraries make Python a go-to language for backend development and
automation tasks.
Specialized Libraries
Beyond the major fields, Python offers specialized libraries for almost any task.
OpenCV is a leading library in computer vision, offering tools for image and video
analysis, facial recognition, and object detection. NLTK and spaCy are popular for
natural language processing, enabling developers to work with human language
data. SQLAlchemy and PyMySQL provide database access, while Requests
simplifies HTTP requests for web communication. Tkinter helps create GUI
applications, and PyGame supports simple game development. The Python
Package Index (PyPI) hosts over 400,000 packages, ensuring that developers can
find a library for virtually any problem. In conclusion, Python’s rich library
ecosystem is a key factor in its popularity and versatility, empowering developers
across industries to build robust, scalable, and intelligent applications with minimal
effort.
Example:
x = 10 # Global variable
def my_function():
x = 5 # Local variable
print("Local x:", x)
my_function()
print("Global x:", x)
Output:
38
Local x: 5
Global x: 10
39
python
my_tuple = (1, 2, 3)
Common Uses:
Represent fixed data: e.g., coordinates (x, y)
Used as dictionary keys
Example:
40
python
c) Set
A set is an unordered, mutable collection of unique elements.
Useful for membership testing and removing duplicates.
Syntax:
python
my_set = {1, 2, 3, 2}
print(my_set) # Output: {1, 2, 3}
Set Operations:
union(), intersection(), difference(), add(), remove()
Example:
python
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
d) Dictionary
A dictionary stores key-value pairs.
Keys must be unique and immutable.
41
Syntax:
python
42
print(dq)
b) defaultdict
Like a dictionary, but provides a default value for missing keys.
c) Counter
Used for counting hashable objects.
Example:
python
43
For example, my_list = [1, 2, 3, 'Python', 4.5] creates a list containing integers, a
string, and a float. Lists are highly flexible and are often used when the order of
elements matters or when the collection needs to be updated frequently. Python
also supports list comprehensions, which offer a concise way to create lists using
loops and conditions. Lists are ideal for storing sequences of items such as names,
numbers, or objects that may need to be changed or re-ordered.
44
should not be altered accidentally, such as fixed configuration values or
coordinates. Python also allows for a single-element tuple using a trailing comma
(e.g., t = (5,)). Tuples support indexing and slicing like lists but lack methods for
modification such as append() or remove(). Their immutability also makes them
hashable, so they can be used as keys in dictionaries, which is not possible with
lists.
Tuple Example Program in Python
# Creating a tuple
fruits = ("apple", "banana", "cherry", "banana")
45
print(fruit)
Output:
46
Tuple Example Program in Python
python
# Tuple creation
student_info = ("John", 21, "Computer Science")
# Length of tuple
print("Total items:", len(student_info))
# Tuple unpacking
name, age, dept = student_info
print(f"Unpacked - Name: {name}, Age: {age}, Dept: {dept}")
Output:
Name: John
Age: 21
Department: Computer Science
Total items: 3
Unpacked - Name: John, Age: 21, Dept: Computer Science
47
Explanation:
A tuple is a collection of ordered, immutable elements.
Elements are accessed using indexing like lists.
Tuples support unpacking, where each value is assigned to a variable.
len() is used to find how many items are in the tuple.
# Accessing values
print("Name:", student["name"])
48
print("Age:", student["age"])
print("Course:", student["course"])
Name: Alice
Age: 20
Course: Data Science
Student Information:
name : Alice
age : 21
course : Data Science
grade : A
49
5.8: Dictionary Methods and Applications
Dictionaries come with a rich set of methods for manipulating key-value pairs.
The get() method safely retrieves a value without raising an error if the key doesn't
exist. The update() method adds or modifies entries, pop() removes a key, and
keys(), values(), and items() allow iteration over the dictionary. You can also use
del to delete keys and in to check for the existence of a key. Dictionaries are
widely used in real-life applications such as storing user data, counting occurrences
(using elements as keys), and implementing lookup tables. They are one of the
most flexible and widely used data structures in Python.
Methods and Applications
What is a Dictionary?
A dictionary in Python is an unordered collection of key-value pairs. It is
mutable, meaning it can be changed after creation.
Syntax:
python
1. dict.keys()
Returns a view object that displays a list of all the keys.
python
50
student = {'name': 'Ali', 'age': 20}
print(student.keys()) # dict_keys(['name', 'age'])
2. dict.values()
Returns a view object of all values.
python
3. dict.items()
Returns a view object of key-value tuple pairs.
python
4. dict.get(key, default)
Returns the value of the specified key. If key not found, returns default value.
python
print(student.get('name')) # Ali
print(student.get('grade', 'N/A')) # N/A
5. dict.update(other_dict)
Updates the dictionary with key-value pairs from another dictionary.
python
51
student.update({'grade': 'A'})
print(student) # {'name': 'Ali', 'age': 20, 'grade': 'A'}
6. dict.pop(key)
Removes the key and returns its value.
python
age = student.pop('age')
print(age) # 20
print(student) # {'name': 'Ali', 'grade': 'A'}
7. dict.popitem()
Removes and returns the last inserted key-value pair.
python
8. dict.clear()
Removes all items from the dictionary.
python
student.clear()
print(student) # {}
52
9. dict.copy()
Returns a shallow copy of the dictionary.
python
config = {
'theme': 'dark',
'font': 'Arial',
'fontsize': 12
}
53
2. Counting Frequency of Elements
python
student = {
'name': 'Divya',
'roll_no': 101,
'marks': {'math': 90, 'science': 88}
}
print(student['marks']['science']) # 88
4. Database-like Storage
python
database = {
54
1001: {'name': 'Amit', 'dept': 'CS'},
1002: {'name': 'Sara', 'dept': 'IT'}
}
print(database[1002]['name']) # Sara
import json
data = '{"name": "John", "age": 30}'
parsed = json.loads(data)
print(parsed['name']) # John
55
are efficient and useful for comparing data collections. Sets also include methods
like add() to insert an element, remove() and discard() to delete items, and clear()
to remove all elements. The in keyword can be used to test membership. Sets are
commonly used in applications such as eliminating duplicate entries from a list,
managing unique user IDs, or filtering data. Their efficiency and built-in methods
make them a handy tool in every Python programmer’s toolkit.
What is a Set?
A set is an unordered, mutable collection of unique elements in Python.
Key Characteristics:
Duplicate elements are not allowed.
Elements must be immutable (e.g., numbers, strings, tuples).
Sets are defined using curly braces {} or the set() constructor.
Example:
python
56
my_set = {1, 2, 3, 3, 2}
print(my_set) # Output: {1, 2, 3}
1. add(element)
Adds an element to the set.
python
s = {1, 2}
s.add(3)
print(s) # {1, 2, 3}
2. remove(element)
Removes the specified element. Raises an error if the element is not found.
python
s.remove(2)
print(s) # {1, 3}
3. discard(element)
Removes the specified element. Does not raise an error if the element is not found.
python
57
s.discard(5) # No error
4. pop()
Removes and returns a random element.
python
item = s.pop()
print(item, s)
5. clear()
Removes all elements from the set.
python
s.clear()
print(s) # set()
6. copy()
Returns a shallow copy of the set.
python
s = {1, 2, 3}
new_s = s.copy()
print(new_s)
58
Set Operations
Sets support many mathematical operations:
1. Union (| or .union())
Returns a set with all elements from both sets (no duplicates).
python
a = {1, 2, 3}
b = {3, 4, 5}
print(a | b) # {1, 2, 3, 4, 5}
print(a.union(b))
3. Difference (- or .difference())
Returns the elements in the first set but not in the second.
python
print(a - b) # {1, 2}
print(a.difference(b))
59
4. Symmetric Difference (^ or .symmetric_difference())
Returns elements in either set but not in both.
python
print(a ^ b) # {1, 2, 4, 5}
print(a.symmetric_difference(b))
Set Comparisons
1. Subset (<=) and Superset (>=)
python
a = {1, 2}
b = {1, 2, 3}
print(a <= b) # True (a is a subset of b)
print(b >= a) # True (b is a superset of a)
x = {1, 2}
y = {3, 4}
print(x.isdisjoint(y)) # True
Applications of Sets
60
1. Removing Duplicates from a List
python
nums = [1, 2, 2, 3, 1]
unique = list(set(nums))
print(unique) # [1, 2, 3]
4. Efficient Lookups
Set lookups are faster than lists for large data.
python
data = set(range(1_000_000))
print(500_000 in data) # Fast
61
Lambda Function?
A lambda function is a small anonymous function in Python.
It is used when you need a simple function for a short period of time.
Key Points:
Defined using the lambda keyword.
Can take any number of arguments.
Has only one expression (no statements like loops or multiple lines).
🧾 Syntax:
python
Example:
python
add = lambda a, b: a + b
print(add(3, 5)) # Output: 8
It is the same as:
python
62
1. Using with map()
Applies a function to all elements in a list.
python
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x*x, numbers))
print(squared) # [1, 4, 9, 16]
numbers = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, numbers))
print(even) # [2, 4, 6]
63
python
square = lambda x: x * x
print(square(6)) # 36
square = lambda x: x * x
print(square(6)) # 36
Practice Examples
Example 1:
python
double = lambda x: x * 2
print(double(4)) # Output: 8
64
Example 2:
python
65
Problem-Solving and Logical Thinking
Improved problem-solving skills through practice exercises and coding tasks that
required logical reasoning and creative thinking.
Real-World Application Readiness
Built confidence to use Python in real-world scenarios including data analysis,
automation, web development, and basic machine learning.
Code Debugging and Optimization
Learned how to write clean, readable code and debug errors efficiently using
Python’s tools and best practices.
66