UNIT 1: Comprehensive Guide to Python: Basics, Control Structures,
and String Handling
SUB-TOPIC 1.1
1. What is Python?
Definition:
Python is a high-level, interpreted, general-purpose programming language known for its easy
readability and simple syntax, which makes it ideal for beginners as well as professionals.
Key Points:
● Created by Guido van Rossum in 1991.
● Interpreted language (no need to compile).
● Supports multiple programming paradigms: procedural, object-oriented, and functional.
● Used in web development, data analysis, AI, machine learning, automation, and more.
2. Features of Python
Feature Description
Easy to Learn Simple syntax similar to English.
Interpreted Code executed line by line, no need for compilation.
Dynamically Typed No need to declare variable types explicitly.
Portable Runs on different operating systems without modification.
Extensive Libraries Large standard library and third-party modules available.
Open Source Free to use and distribute.
Object-Oriented Supports classes and objects, reusable code.
High-level Language Abstracts away low-level details like memory management.
3. Installation of Python
Step-by-step Installation:
1. Go to the official website: python.org
2. Download the latest version compatible with your OS (Windows, Mac, Linux).
3. Run the installer:
o On Windows, check "Add Python to PATH" during installation.
4. Verify installation:
o Open Command Prompt (Windows) or Terminal (Mac/Linux).
o Type python --version or python3 --version.
o If version info appears, Python is installed correctly.
4. Running Python Programs
Modes of Running Python Code:
Mode Description
Interactive Run Python commands one by one in Python shell or REPL (Read-Eval-Print Loop).
Mode Ideal for testing small code snippets.
Script Mode Write code in a .py file and run the entire program. Best for longer programs.
Example:
● Interactive Mode:
>>> print("Hello, World!")
Hello, World!
>>> 2 + 3
● Script Mode:
Create a file named hello.py:
print("Hello, World!")
Run it from the terminal:
python hello.py
5. Variables in Python
Definition:
Variables are containers that hold data values.
Key Points:
● Variables do not need explicit declaration of data type.
● Variable names can contain letters, digits, and underscores but cannot start with a digit.
● Python is case sensitive (age and Age are different).
Example:
name = "Alice"
age = 21
pi = 3.14
6. Keywords in Python
Keywords are reserved words that have special meaning and cannot be used as variable names.
Some Python Keywords:
Keyword Purpose Keyword Purpose
if Conditional statement def Define function
else Alternative branch while Loop
for Loop return Return value
True Boolean True False Boolean False
Keyword Purpose Keyword Purpose
None Represents null value class Define class
7. Data Types in Python
Data Type Description Example
int Integer numbers x=5
float Decimal numbers pi = 3.1416
str Sequence of characters (text) name = "Bob"
bool Boolean values (True or False) is_valid = True
list Ordered, mutable collection numbers = [1, 2, 3]
tuple Ordered, immutable collection coords = (4, 5)
dict Key-value pairs person = {"age": 25}
8. Type Conversion
Definition:
Converting data from one type to another.
Common Conversions:
Function Converts To Example
int() Integer int("10") → 10
float() Floating-point number float(5) → 5.0
str() String str(10) → "10"
Function Converts To Example
bool() Boolean bool(0) → False
9. Operators in Python
Operator
Operators Example Description
Type
+, -, *, /, Addition, subtraction, multiplication, division,
Arithmetic 5+3=8
%, //, ** modulus, floor division, exponentiation
Compariso ==, !=, >, <,
5 > 3 → True Compare values
n >=, <=
True and False
Logical and, or, not Logical operations
→ False
Assignmen x += 1 (same as
=, +=, -=, etc. Assign or update variables
t x = x + 1)
Bitwise &, ` , ^, ~, <<, >>` Operate on bits
10. Comments in Python
Definition:
Comments are lines ignored by the interpreter, used to explain code.
● Single-line comment: starts with #
# This is a comment
print("Hello") # Inline comment
● Multi-line comment: triple quotes (''' ''' or """ """)
"""
This is a
multi-line comment
"""
11. Input and Output Functions
Input Function: input()
● Takes input from the user as a string.
Example:
name = input("Enter your name: ")
print("Hello, " + name)
Output Function: print()
● Displays output on the screen.
● Can print multiple items separated by commas.
Example:
print("Sum of 2 and 3 is", 2 + 3)
12. Practical Code Example (All Concepts Combined)
# Program: Greet User and Calculate Age Next Year
# Input name
name = input("Enter your name: ")
# Input age (string by default), convert to integer
age = int(input("Enter your age: "))
# Calculate age next year
next_age = age + 1
# Output message
print("Hello,", name + "!")
print("Next year, you will be", next_age, "years old.")
SUB-TOPIC 1.2
1. Control Structures: Definition
Control structures are blocks of programming that determine the flow of control in a program —
deciding which statements execute, how many times, and under what conditions.
2. Conditional Statements: if, else, elif
Definition:
● Used to execute different code based on conditions.
Syntax and Explanation:
if condition:
# block executed if condition is True
elif another_condition:
# executed if first condition is False but this one is True
else:
# executed if none of the above conditions are True
Example:
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible to vote.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
3. Loops in Python
Loops help repeat a block of code multiple times.
4. for Loops
Simple for Loop:
● Used to iterate over a sequence (list, string, range).
for i in [1, 2, 3, 4]:
print(i)
For Loop Using range()
● range(start, stop, step) generates numbers within a range.
Example:
for i in range(1, 6): # prints 1 to 5
print(i)
5. while Loops
● Repeats as long as the condition is True.
count = 1
while count <= 5:
print(count)
count += 1
6. Loop Manipulation: continue, break, and else
Keywo
Purpose Example Use
rd
break Exits the loop immediately Stop loop on certain condition
contin
Skips current iteration and moves to next Skip processing for a specific value
ue
Executes after loop finishes normally (no Run code after loop completes
else
break) normally
7. Examples of Loop Control Statements
for i in range(1, 6):
if i == 3:
continue # skip 3
print(i)
# Output: 1 2 4 5
count = 1
while count <= 5:
if count == 4:
break # exit loop when count is 4
print(count)
count += 1
# Output: 1 2 3
for i in range(3):
print(i)
else:
print("Loop ended normally.")
Summary Table: Control Structures
Control Structure Usage Syntax Example
if Execute if condition is True if x > 0:
elif Additional conditions elif x == 0:
else Default if no conditions match else:
for Iterate over a sequence for i in range(5):
while Repeat while condition True while count < 5:
break Exit loop immediately if i == 3: break
continue Skip current iteration if i == 3: continue
else with loop Run after loop completes normally for ... else:
SUB-TOPIC 1.3
1. What is a String?
A string is a sequence of characters enclosed within quotes (single '...', double "...", or triple '''...''').
2. Characteristics of Strings
Characteristi
Description
c
Immutable Strings cannot be changed after creation
Indexed Each character has a position, starting at 0 (left to right)
Iterable You can loop through each character in a string
3. Accessing String Elements
Indexing:
● Access single characters using their index.
name = "Python"
print(name[0]) # Output: P
print(name[-1]) # Output: n (last character)
Slicing:
● Extract substrings using [start:end:step].
text = "Hello World"
print(text[0:5]) # Output: Hello
print(text[6:]) # Output: World
print(text[::-1]) # Output: dlroW olleH (reversed)
4. Looping Through Strings
for ch in "Python":
print(ch)
5. Searching in Strings
Metho
Description Returns Example
d
Index or -
find() Finds first occurrence, -1 if not found "hello".find('e') → 1
1
index() Finds first occurrence, error if not found Index "hello".index('l') → 2
count() Counts occurrences Integer "hello".count('l') → 2
6. String Methods
Method Description Example Output
upper() Converts to uppercase "hello".upper() "HELLO"
lower() Converts to lowercase "HELLO".lower() "hello"
Method Description Example Output
title() Capitalizes first letter of each word "hello world".title() "Hello World"
swapcase() Swaps case of each letter "Hello".swapcase() "hELLO"
capitalize() Capitalizes first letter of string "hello".capitalize() "Hello"
replace() Replaces substring "hello".replace('l', 'p') "heppo"
split() Splits string into list by separator "a,b,c".split(',') ['a', 'b', 'c']
join() Joins list elements into a string ','.join(['a','b','c']) "a,b,c"
startswith() Checks if string starts with substring "hello".startswith('he') True
endswith() Checks if string ends with substring "hello".endswith('lo') True
isalpha() Checks if all characters are alphabets "hello".isalpha() True
isdigit() Checks if all characters are digits "123".isdigit() True
7. String Comparison
Strings can be compared lexicographically (alphabetical order).
print("apple" == "Apple") # False (case-sensitive)
print("apple" > "Apple") # True (lowercase > uppercase in ASCII)
8. String Operations
Operation Example Output Description
"Hello " + "Hello
Concatenation (+) Join two strings
"World" World"
Repetition (*) "Hi" * 3 "HiHiHi" Repeat string multiple times
Membership
'a' in "apple" True Check if substring exists
Testing
'z' not in "apple" True Check if substring does NOT exist
9. Practical Examples:
# Accessing and slicing
text = "Programming"
print(text[0]) #P
print(text[3:6]) # gra
print(text[::-1]) # gnimmargorP
# String methods
name = "john doe"
print(name.title()) # John Doe
print(name.upper()) # JOHN DOE
print(name.replace("john", "Jane")) # Jane doe
# Searching
sentence = "Hello world, welcome to Python"
print(sentence.find("welcome")) # 12
print(sentence.count("o")) #4
# Concatenation and repetition
print("Hi " + "there") # Hi there
print("Bye! " * 3) # Bye! Bye! Bye!
# Membership
print("P" in text) # True
print("z" not in text) # True
UNIT 2: Python Data Structures, Functions, and Modules
SUB-TOPIC 2.1
1. Lists
What is a List?
A List in Python is an ordered, mutable (can be changed), and heterogeneous (can
contain different data types) collection of items.
List Characteristics:
● Ordered: Items have a defined order and can be accessed by index.
● Mutable: You can modify, add or remove items.
● Allows duplicates: Same value can appear multiple times.
● Heterogeneous: Items can be of any data type (integers, strings, other lists, etc.).
● Dynamic size: Lists can grow or shrink as needed.
Creating a List:
# Empty list
my_list = []
# List of integers
numbers = [10, 20, 30, 40]
# Mixed data types
mixed = [1, "hello", 3.14, True]
# Nested list
nested = [1, 2, [3, 4, 5], 6]
Accessing and Updating Elements in List
Indexing:
● Starts from 0.
● Negative indexing starts from -1 (last element).
lst = [10, 20, 30, 40]
print(lst[0]) # 10 (first element)
print(lst[-1]) # 40 (last element)
Slicing:
● Extract parts of list: lst[start:end] (end not included).
print(lst[1:3]) # [20, 30]
print(lst[:2]) # [10, 20]
print(lst[2:]) # [30, 40]
Nested List Access:
nested = [1, 2, [3, 4, 5], 6]
print(nested[2]) # [3, 4, 5]
print(nested[2][1]) # 4
Traversing a List
Loop through each element:
for item in lst:
print(item)
Deleting Elements from a List
Method Description Example
del Delete element by index or entire list del lst[1]
remove Remove first occurrence of a value lst.remove(20)
()
pop() Remove and return element by index (default lst.pop() or lst.pop(1)
last)
lst = [10, 20, 30, 40]
del lst[1] # lst = [10, 30, 40]
lst.remove(30) # lst = [10, 40]
popped = lst.pop() # popped=40, lst=[10]
List Operations
Operatio Description Example
n
+ Concatenate lists [1, 2] + [3, 4] → [1, 2, 3, 4]
* Repeat list [1, 2] * 3 → [1, 2, 1, 2, 1, 2]
elements
in Check 3 in [1, 2, 3] → True
membership
len() Length of list len([1,2,3]) → 3
Built-in List Functions
Function Description Example
len() Returns number of len([1,2,3]) → 3
elements
max() Returns max element max([1,5,3]) → 5
min() Returns min element min([1,5,3]) → 1
sum() Sum of numeric elements sum([1,2,3]) → 6
clear() Empties the list lst.clear()
List Methods
Method Description Example
append(x) Adds element x to the end lst.append(5)
extend(iterable) Extends list by appending elements from lst.extend([6,7])
iterable
insert(i, x) Insert x at index i lst.insert(2, 10)
remove(x) Removes first occurrence of x lst.remove(10)
pop([i]) Removes and returns element at index i (last lst.pop() or lst.pop(1)
if no index)
index(x) Returns index of first occurrence of x lst.index(5)
count(x) Returns number of occurrences of x lst.count(5)
sort() Sorts the list in ascending order lst.sort()
reverse() Reverses the list in-place lst.reverse()
2. Tuples
What is a Tuple?
A Tuple is an ordered, immutable (cannot be changed), and heterogeneous collection
of items.
Tuple Characteristics:
● Ordered: Items are indexed.
● Immutable: Elements cannot be modified after creation.
● Allows duplicates.
● Heterogeneous: Can contain multiple data types.
● Usually used when fixed data is needed.
Creating a Tuple:
empty_tuple = ()
single_element = (5,) # Note the trailing comma for a single element
tuple1 = (1, 2, 3)
mixed = (1, "apple", 3.14)
nested_tuple = (1, 2, (3, 4))
Accessing Values in Tuples
● Indexing and Slicing similar to lists.
t = (10, 20, 30, 40)
print(t[0]) # 10
print(t[-1]) # 40
print(t[1:3]) # (20, 30)
● Access nested tuple:
nested = (1, 2, (3, 4))
print(nested[2][1]) # 4
Tuple Assignment
a, b, c = (1, 2, 3) # Unpacking
print(a) # 1
print(b) # 2
print(c) # 3
Tuples as Return Values
Functions can return multiple values packed into a tuple:
def get_min_max(numbers):
return min(numbers), max(numbers)
minimum, maximum = get_min_max([1, 2, 3, 4])
print(minimum, maximum) # 1 4
Packing and Unpacking
● Packing: Group values into a tuple.
packed = 1, 2, 3
● Unpacking: Assign tuple elements to variables.
x, y, z = packed
Variable-length Argument Tuple
Using *args to accept variable number of arguments in functions:
def sum_all(*args):
total = 0
for num in args:
total += num
return total
print(sum_all(1, 2, 3)) # 6
print(sum_all(4, 5)) #9
Tuple Operations
Operatio Description Example
n
+ Concatenate (1, 2) + (3, 4) → (1, 2, 3, 4)
tuples
* Repeat tuples (1, 2) * 3 → (1, 2, 1, 2, 1, 2)
in Membership test 3 in (1, 2, 3) → True
Iteration on Tuples
t = (10, 20, 30)
for item in t:
print(item)
Built-in Tuple Functions
Function Description Example
len() Number of elements len((1,2,3)) → 3
max() Max element max((1,5,3)) → 5
min() Min element min((1,5,3)) → 1
sum() Sum of numeric elements sum((1,2,3)) → 6
count(x) Counts occurrences of x (1,2,2,3).count(2) → 2
sorted() Returns sorted list (tuple remains sorted((3,1,2)) → [1, 2, 3]
immutable)
Differences between List and Tuple
Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot be
changed)
Syntax Square brackets [ ] Parentheses ( )
Performance Slightly slower Faster due to immutability
Use case Collections that change Fixed collections
Methods Many methods (append, Few methods
remove)
Memory Uses more memory Uses less memory
efficiency
Practical Examples
Example 1: Creating and modifying a list
fruits = ['apple', 'banana', 'cherry']
print(fruits[1]) # banana
fruits.append('orange')
fruits.remove('banana')
print(fruits) # ['apple', 'cherry', 'orange']
Example 2: Tuple unpacking
coordinates = (10, 20)
x, y = coordinates
print(f"x = {x}, y = {y}") # x = 10, y = 20
Example 3: Using list methods and functions
numbers = [5, 3, 8, 6]
numbers.sort()
print(numbers) # [3, 5, 6, 8]
print(sum(numbers)) # 22