Python Programming
Lecture Notes
Composed By : Mr. Naved Ahmad
Course: Python Programming for [Link]
Level: Beginner • Semester I
Department of Computer Science & Engineering
Topics Covered:
• Basics of Programming Languages • Operators & Expressions
• Python IDE & Programming Cycle • Conditional Statements
• Data Types & Type Conversion • Loops
• Variables & Garbage Collection • Data Structures
• Strings • Functions
• Sets & Dictionaries • File Handling
NOTE: These notes are designed for students with
programming experience.
Every concept is explained with real-life analogies, examples, and
common mistakes.
Python Programming Notes [Link] – Beginner Level
Contents
1 Basics of Programming Languages 3
1.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2 High-Level Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.2.1 Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3 Low-Level Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.3.1 Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
1.4 Compiler vs Interpreter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.1 What is a Compiler? . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.4.2 What is an Interpreter? . . . . . . . . . . . . . . . . . . . . . . . . 4
2 The Programming Cycle for Python 4
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
2.2 Steps in the Programming Cycle . . . . . . . . . . . . . . . . . . . . . . . . 5
2.3 Python IDE (Integrated Development Environment) . . . . . . . . . . . . . 5
2.3.1 What is an IDE? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.4 Interacting with Python Programs . . . . . . . . . . . . . . . . . . . . . . . 5
2.4.1 Two Modes in Python . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.5 Elements of Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.6 Type Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.6.1 What is Type Conversion? . . . . . . . . . . . . . . . . . . . . . . . 7
3 Basics: Expressions, Operators and Operator Precedence 8
3.1 Expressions and Assignment Statement . . . . . . . . . . . . . . . . . . . . 8
3.1.1 What is an Expression? . . . . . . . . . . . . . . . . . . . . . . . . 8
3.1.2 What is an Assignment Statement? . . . . . . . . . . . . . . . . . . 8
3.2 Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
3.3 Relational (Comparison) Operators . . . . . . . . . . . . . . . . . . . . . . 9
3.4 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.5 Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
3.6 Boolean Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4 Conditional Statements in Python 12
4.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.2 The if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.3 The if-else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
4.4 The elif Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
4.5 Nested if Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
5 Variable Assignment and Garbage Collection 14
5.1 Variable Assignment in Python . . . . . . . . . . . . . . . . . . . . . . . . 14
5.2 Garbage Collection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
5.3 Identity Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
5.4 Membership Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
6 Python Data Structures: Tuples and Lists 17
6.1 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
6.1.1 What is a Tuple? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Prepared for Classroom Use 1 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
6.1.2 Unpacking Sequences . . . . . . . . . . . . . . . . . . . . . . . . . . 17
6.1.3 Tuple Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
6.2 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
6.2.1 What is a List? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
6.3 Slicing (Lists and Tuples) . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
7 Loops in Python 20
7.1 Introduction to Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
7.2 The while Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
7.3 The for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
7.4 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
7.5 break and continue Statements . . . . . . . . . . . . . . . . . . . . . . . . 23
8 Bitwise Operators 24
8.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
9 Mutable and Immutable Sequences 24
9.1 Explanation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
9.2 List Comprehension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
10 Sets 26
10.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
10.2 Set Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
11 Dictionaries 28
11.1 What is a Dictionary? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
11.2 Nested Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
11.3 Working with Multiple Data Structures . . . . . . . . . . . . . . . . . . . . 29
12 Strings 30
12.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
12.2 String Length, Concatenation and Repetition . . . . . . . . . . . . . . . . 30
12.3 Indexing and Slicing of Strings . . . . . . . . . . . . . . . . . . . . . . . . . 30
12.4 Built-in String Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
13 Functions 32
13.1 What is a Function? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.2 Parts of a Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
13.3 Keyword and Default Arguments . . . . . . . . . . . . . . . . . . . . . . . 33
13.4 Scope Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
13.5 Lambda Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
14 File Handling 35
14.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
14.2 File Modes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
14.3 Reading and Writing Text Files . . . . . . . . . . . . . . . . . . . . . . . . 35
14.4 Appending to Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
14.5 Working with CSV Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
15 Quick Revision Summary 37
Prepared for Classroom Use 2 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
1 Basics of Programming Languages
1.1 Introduction
What is a Program?
A program is a set of instructions given to a computer to perform a specific task.
Just like you give step-by-step instructions to a friend to make tea, a program gives
step-by-step instructions to a computer.
A programming language is a special language used to write these instructions. Com-
puters only understand 0s and 1s (binary), so programming languages help us write
instructions in a way humans can understand, which is then converted to binary.
1.2 High-Level Languages
1.2.1 Explanation
High-Level Languages are programming languages that are close to human lan-
guage. They are easy to read, write, and understand. You do not need to know how the
computer hardware works internally.
Real-Life Analogy: Imagine ordering food at a restaurant. You just say “Give me a
pizza” – you do not care how the chef makes it. High-level languages work the same way
– you write simple instructions and the computer handles the complex details.
Examples: Python, Java, C++, JavaScript, Ruby
Advantages:
Easy to write and understand
Less code needed for complex tasks
Can run on different types of computers
Easier to debug (find and fix errors)
1.3 Low-Level Languages
1.3.1 Explanation
Low-Level Languages are programming languages that are close to machine lan-
guage (0s and 1s). They are harder to write but give direct control over the hardware.
Real-Life Analogy: If high-level is ordering at a restaurant, low-level is going into the
kitchen yourself and cooking every step manually.
Types:
1. Machine Language – Pure binary (0s and 1s). Directly understood by the
CPU.
2. Assembly Language – Uses short codes like MOV, ADD, SUB instead of 0s and
1s.
Prepared for Classroom Use 3 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Feature High-Level Language Low-Level Language
Readability Easy to read Very difficult
Speed Slower execution Faster execution
Hardware Con- Limited Full control
trol
Examples Python, Java Assembly, Machine Code
Use Case General applications Operating systems, Drivers
1.4 Compiler vs Interpreter
1.4.1 What is a Compiler?
A compiler reads the entire program first, translates it all at once into machine code,
and then executes it. If there are errors, it shows all errors at once after reading the full
program.
Analogy: A compiler is like a translator who reads an entire book in French, translates
the whole book to English, and then gives you the translated book to read.
Languages using Compiler: C, C++, Java (partially)
1.4.2 What is an Interpreter?
An interpreter reads and executes the program line by line. It translates one line,
executes it, then goes to the next line. If there is an error on line 5, it stops at line 5.
Analogy: An interpreter is like a live translator who listens to a French speaker sentence
by sentence and immediately tells you what they said.
Languages using Interpreter: Python, JavaScript, Ruby
Feature Compiler Interpreter
Translation Entire program at once Line by line
Speed Faster after compilation Slower
Error Detection All errors after full scan Stops at first error
Python uses No Yes
Key Point: Python uses an Interpreter
Python is an interpreted language. This means Python reads and runs your code
line by line. This makes it great for learning because you can test small pieces of code
instantly!
2 The Programming Cycle for Python
2.1 Introduction
The programming cycle is the series of steps a programmer follows to solve a problem
using code.
Prepared for Classroom Use 4 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
2.2 Steps in the Programming Cycle
Step 1. Understand the Problem – Read the problem carefully. What do you need
to find out?
Step 2. Plan the Solution (Algorithm) – Write the steps (in plain English or a
flowchart) to solve the problem.
Step 3. Write the Code – Translate your plan into Python code.
Step 4. Test the Code – Run the code and check if it gives the correct output.
Step 5. Debug – If there are errors, find and fix them.
Step 6. Repeat if Needed – Go back and improve the code if needed.
2.3 Python IDE (Integrated Development Environment)
2.3.1 What is an IDE?
An IDE is a software application that provides everything you need to write, run, and
test your code – all in one place. Think of it like Microsoft Word for code.
Popular Python IDEs:
IDLE – Comes built-in with Python. Simple and great for beginners.
VS Code – Free, popular, and very powerful.
PyCharm – Professional IDE, many helpful features.
Jupyter Notebook – Great for data science; runs code in cells.
Thonny – Designed specifically for Python beginners.
Google Colab – Free, runs in your browser, no installation needed.
2.4 Interacting with Python Programs
2.4.1 Two Modes in Python
1. Interactive Mode – You type one command, Python runs it immediately.
Use this in the IDLE shell or terminal.
2. Script Mode – You write a full program in a .py file, then run it.
Example 1: Interactive Mode (in Python Shell)
1 >>> print ( " Hello , World ! " )
2 Hello , World !
3 >>> 5 + 3
4 8
5 >>> name = " Alice "
6 >>> print ( " Hello " , name )
7 Hello Alice
Line-by-line explanation:
Prepared for Classroom Use 5 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
print("Hello, World!") – Displays the text Hello, World! on screen.
5 + 3 – Python calculates and shows the result 8.
name = "Alice" – Stores the word “Alice” in a variable called name.
print("Hello", name) – Displays Hello followed by the value in name.
Example 2: Script Mode (save as [Link], then run)
1 # This is a Python script
2 name = input ( " Enter your name : " )
3 age = input ( " Enter your age : " )
4 print ( " Hello " , name , " ! You are " , age , " years old . " )
Line-by-line explanation:
# This is a Python script – A comment. Python ignores lines starting
with #.
input() – Takes input from the user through the keyboard.
The last print() – Shows the greeting with name and age.
2.5 Elements of Python
Element Description Example
Keywords Reserved words in if, else, for,
Python while, def
Identifiers Names given to variables, age, total,
functions myFunction
Literals Fixed values 5, 3.14, "hello",
True
Operators Symbols to perform oper- +, -, *, /, ==
ations
Comments Notes in code (ignored by # this is a comment
Python)
Indentation Spaces at start of a line 4 spaces before a block
(very important!)
Common Mistake: Ignoring Indentation
Python uses indentation (spaces) instead of curly braces {} to define code blocks.
Missing or wrong indentation causes an IndentationError!
Wrong: if x > 0:
print("positive") ← this will cause an error
Correct: if x > 0:
print("positive") ← 4 spaces indentation
Prepared for Classroom Use 6 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
2.6 Type Conversion
2.6.1 What is Type Conversion?
Type Conversion means changing a value from one data type to another. For example,
converting the number 5 (integer) into the string “5” (text).
Two Types:
1. Implicit Conversion – Python does it automatically.
2. Explicit Conversion – You do it manually using conversion functions.
Conversion Functions:
Function Description Example
int() Converts to integer int("5") → 5
float() Converts to float float("3.14") →
3.14
str() Converts to string str(100) → ”100”
bool() Converts to boolean bool(0) → False
list() Converts to list list("abc") →
[’a’,’b’,’c’]
Example 1: Implicit Type Conversion
1 # Python automatically converts int to float
2 x = 5 # integer
3 y = 2.5 # float
4 result = x + y
5 print ( result ) # Output : 7.5
6 print ( type ( result ) ) # Output : < class ’ float ’>
Example 2: Explicit Type Conversion
1 # Convert string input to integer for calculation
2 age = input ( " Enter your age : " ) # input () always returns a
string
3 age = int ( age ) # convert string to
integer
4 next_year = age + 1
5 print ( " Next year you will be : " , next_year )
Example 3: Multiple Conversions
1 num_str = " 100 "
2 num_int = int ( num_str ) # "100" -> 100
3 num_float = float ( num_str ) # "100" -> 100.0
4 num_back = str ( num_int ) # 100 -> "100"
5
Prepared for Classroom Use 7 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
6 print ( num_int ) # 100
7 print ( num_float ) # 100.0
8 print ( num_back ) # 100
9 print ( type ( num_int ) ) # < class ’ int ’>
10 print ( type ( num_float ) ) # < class ’ float ’>
Common Errors in Type Conversion
int("hello") → ValueError – Cannot convert text to number!
int("3.14") → ValueError – Use float() first, then int()
int(float("3.14")) → 3 – This works correctly
3 Basics: Expressions, Operators and Operator Precedence
3.1 Expressions and Assignment Statement
3.1.1 What is an Expression?
An expression is any combination of values, variables, and operators that Python can
evaluate (calculate) to produce a result.
Examples: 5 + 3, x * 2, age > 18, "Hello" + " World"
3.1.2 What is an Assignment Statement?
An assignment statement stores a value into a variable using the = symbol.
Syntax: variable name = value
Example: Assignment Statements
1 name = " Alice " # stores string in variable name
2 age = 20 # stores integer in variable age
3 price = 99.99 # stores float in variable price
4 is_student = True # stores boolean in variable is_student
5 x = y = z = 0 # assign same value to multiple
variables
6 a, b, c = 1, 2, 3 # assign different values in one line
7
8 print ( name , age , price ) # Alice 20 99.99
9 print (x , y , z ) # 0 0 0
10 print (a , b , c ) # 1 2 3
3.2 Arithmetic Operators
Arithmetic operators are used to perform mathematical calculations.
Prepared for Classroom Use 8 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Operator Description Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 3 7
* Multiplication 10 * 3 30
/ Division (float result) 10 / 3 3.333...
// Floor Division (inte- 10 // 3 3
ger result)
% Modulus (remainder) 10 % 3 1
** Exponentiation 2 ** 3 8
(power)
Example: All Arithmetic Operators
1 a = 17
2 b = 5
3
4 print ( " Addition : " , a + b ) # 22
5 print ( " Subtraction : " , a - b ) # 12
6 print ( " Multiplication : " , a * b ) # 85
7 print ( " Division : " , a / b ) # 3.4
8 print ( " Floor Division : " , a // b ) # 3 ( no decimal part )
9 print ( " Modulus : " , a % b ) # 2 ( remainder when 17 /
5)
10 print ( " Power : " , a ** b ) # 1419857 (17 to the power
5)
3.3 Relational (Comparison) Operators
Relational operators compare two values and return either True or False.
Operator Description Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
¿ Greater than 10 > 7 True
¡ Less than 5 < 3 False
¿= Greater than or equal to 5 >= 5 True
¡= Less than or equal to 4 <= 3 False
Example: Relational Operators
1 x = 10
2 y = 20
3
4 print ( x == y ) # False (10 is not equal to 20)
5 print ( x != y ) # True (10 is not equal to 20)
6 print ( x > y) # False (10 is not greater than 20)
7 print ( x < y) # True (10 is less than 20)
Prepared for Classroom Use 9 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
8 print ( x >= 10) # True (10 is equal to 10)
9 print ( y <= 15) # False (20 is not less than or equal to 15)
3.4 Logical Operators
Logical operators combine multiple conditions. They return True or False.
OperatorDescription Example Result
and True only if BOTH conditions (5¿3) and (10¿7) True
are True
or True if AT LEAST ONE con- (5¿3) or (10¡7) True
dition is True
not Reverses the result not(5¿3) False
Example: Logical Operators
1 age = 20
2 has_id = True
3
4 # ’ and ’ - both must be True
5 print ( age >= 18 and has_id ) # True
6
7 # ’ or ’ - at least one must be True
8 print ( age < 18 or has_id ) # True
9
10 # ’ not ’ - reverses the boolean
11 print ( not has_id ) # False
12
13 # Real - world : check if eligible to vote
14 is_citizen = True
15 print ( " Can vote : " , age >= 18 and is_citizen ) # True
3.5 Operator Precedence
Operator Precedence determines the order in which operations are performed when
there are multiple operators in an expression. Think of it like BODMAS/PEMDAS in
mathematics.
Prepared for Classroom Use 10 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Priority Operator Description
1 (Highest) () Parentheses
2 ** Exponentiation
3 +x, -x Unary plus/minus
4 *, /, //, % Multiplication, Divi-
sion
5 +, - Addition, Subtraction
6 ==, !=, >, <, >=, Comparison
<=
7 not Logical NOT
8 and Logical AND
9 (Lowest) or Logical OR
Example: Operator Precedence
1 # Without parentheses - follows precedence rules
2 result1 = 2 + 3 * 4 # 3*4=12 first , then 2+12 = 14
3 print ( result1 ) # 14
4
5 # With parentheses - parentheses first
6 result2 = (2 + 3) * 4 # 2+3=5 first , then 5*4 = 20
7 print ( result2 ) # 20
8
9 # Complex example
10 result3 = 2 ** 3 + 4 * 2 - 1
11 # Step 1: 2**3 = 8
12 # Step 2: 4*2 = 8
13 # Step 3: 8 + 8 - 1 = 15
14 print ( result3 ) # 15
3.6 Boolean Expressions
A Boolean expression is any expression that evaluates to either True or False.
Example: Boolean Expressions
1 x = 15
2
3 # Simple boolean expressions
4 print ( x > 10) # True
5 print ( x == 20) # False
6
7 # Combined boolean expressions
8 print ( x > 10 and x < 20) # True (15 is between 10 and 20)
9 print ( x < 5 or x > 10) # True (15 is greater than 10)
10 print ( not ( x == 15) ) # False ( x IS 15 , so not True =
False )
11
Prepared for Classroom Use 11 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
12 # Storing boolean result in variable
13 is_teenager = ( x >= 13 and x <= 19)
14 print ( is_teenager ) # True
4 Conditional Statements in Python
4.1 Introduction
Conditional statements allow a program to make decisions. Based on whether a con-
dition is True or False, the program executes different blocks of code.
Real-Life Analogy: If it is raining, take an umbrella. Otherwise, wear sunglasses. This
is exactly how if-else works!
4.2 The if Statement
Syntax:
1 if condition :
2 # code to run if condition is True
Example 1: Simple if statement
1 marks = 75
2
3 if marks >= 40:
4 print ( " You have PASSED the exam ! " )
5
6 # If marks were less than 40 , nothing would be printed
Line-by-line explanation:
marks = 75 – Store the value 75 in variable marks.
if marks >= 40: – Check if marks is 75 or more. It is, so enter the block.
print(...) – Since condition is True, this line runs.
4.3 The if-else Statement
Syntax:
1 if condition :
2 # code if condition is True
3 else :
4 # code if condition is False
Prepared for Classroom Use 12 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Example 2: if-else – Pass or Fail
1 marks = int ( input ( " Enter your marks : " ) )
2
3 if marks >= 40:
4 print ( " Result : PASS " )
5 print ( " Congratulations ! " )
6 else :
7 print ( " Result : FAIL " )
8 print ( " Please study harder . " )
9
10 print ( " Exam result declared . " ) # runs regardless of
condition
Line-by-line explanation:
int(input(...)) – Takes user input and converts it to integer.
if marks >= 40: – If marks is 40 or above, go into the if block.
else: – If the if condition was False, go into this block.
The last print() – Runs regardless because it is outside the if-else.
4.4 The elif Statement
elif means “else if”. It allows you to check multiple conditions one after another.
Syntax:
1 if condition1 :
2 # code
3 elif condition2 :
4 # code
5 elif condition3 :
6 # code
7 else :
8 # code if none of the above
Example 3: Grading System using elif
1 marks = int ( input ( " Enter marks (0 -100) : " ) )
2
3 if marks >= 90:
4 grade = " A + "
5 elif marks >= 80:
6 grade = " A "
7 elif marks >= 70:
8 grade = " B "
9 elif marks >= 60:
10 grade = " C "
11 elif marks >= 40:
Prepared for Classroom Use 13 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
12 grade = " D "
13 else :
14 grade = " F "
15
16 print ( " Your Grade is : " , grade )
How it works: Python checks conditions from top to bottom. As soon as one condition
is True, it executes that block and skips the rest.
4.5 Nested if Statement
A nested if is an if statement inside another if statement.
Example 4: Nested if – Voter Eligibility
1 age = int ( input ( " Enter your age : " ) )
2 is_citizen = input ( " Are you a citizen ? ( yes / no ) : " )
3
4 if age >= 18:
5 if is_citizen == " yes " :
6 print ( " You are eligible to vote ! " )
7 else :
8 print ( " You must be a citizen to vote . " )
9 else :
10 print ( " You are too young to vote . " )
11 print ( " Minimum age required is 18. " )
Line-by-line explanation:
The outer if age >= 18 checks the age condition first.
Only if age is 18+, does Python check the inner if is citizen == "yes".
If age is below 18, Python skips the inner if and shows the last message.
Common Errors in Conditional Statements
Using = instead of == for comparison: if x = 5 is WRONG, use if x == 5
Forgetting the colon : at the end of if, else, elif
Incorrect indentation inside the if block
Writing else if instead of elif (Python uses elif, not else if)
5 Variable Assignment and Garbage Collection
5.1 Variable Assignment in Python
Analogy: A variable is like a labelled box. You put a value in the box and give it a
name. You can change what is in the box at any time.
Prepared for Classroom Use 14 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Example: Variable Assignment
1 x = 10 # x points to object 10
2 y = x # y also points to same object 10
3 x = 20 # x now points to new object 20
4
5 print ( x ) # 20
6 print ( y ) # 10 ( y still points to the original 10)
7 print ( id ( x ) ) # memory address of x
8 print ( id ( y ) ) # memory address of y ( different from x now )
5.2 Garbage Collection
Garbage Collection is Python’s automatic memory management system. When an
object is no longer being used (no variable is pointing to it), Python automatically deletes
it from memory to free up space.
Analogy: Imagine a whiteboard in class. When a topic is no longer needed (no one is
referring to it), the professor erases it to make room for new content. Python does the
same with memory!
Example: Garbage Collection in Action
1 import sys
2
3 x = [1 , 2 , 3 , 4 , 5]
4 print ( sys . getrefcount ( x ) ) # reference count > 1
5
6 y = x # y also points to same list
7 print ( sys . getrefcount ( x ) ) # count increases
8
9 del y # remove y reference
10 # Python checks : is anyone still using [1 ,2 ,3 ,4 ,5]?
11 # Yes , x still points to it . So it is NOT deleted .
12
13 del x # remove x reference too
14 # Now NO variable points to [1 ,2 ,3 ,4 ,5]
15 # Python ’s garbage collector will delete it !
Key Points about Garbage Collection
Python uses Reference Counting – tracks how many variables point to an
object.
When the count reaches zero, the memory is automatically freed.
You do not need to manually manage memory in Python (unlike C/C++).
You can manually delete a variable using del variable name.
Prepared for Classroom Use 15 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
5.3 Identity Operator
The identity operator checks whether two variables refer to the same object in mem-
ory (not just equal values).
Operator Description Example
is Returns True if both point to x is y
same object
is not Returns True if they are different x is not y
objects
Example: Identity Operators
1 a = [1 , 2 , 3]
2 b = a # b points to SAME list as a
3 c = [1 , 2 , 3] # c is a NEW list ( different object )
4
5 print ( a is b ) # True ( same object in memory )
6 print ( a is c ) # False ( different objects , same values )
7 print ( a == c ) # True ( same values , but different
objects )
8 print ( a is not c ) # True ( they are not the same object )
9 print ( id ( a ) ) # memory address of a
10 print ( id ( b ) ) # same address as a
11 print ( id ( c ) ) # different address
5.4 Membership Operator
The membership operator checks whether a value exists inside a sequence (string, list,
tuple, etc.).
Operator Description Example
in Returns True if value is found 5 in [1,2,5]
not in Returns True if value is NOT "z" not in "hello"
found
Example: Membership Operators
1 fruits = [ " apple " , " banana " , " mango " , " orange " ]
2
3 print ( " mango " in fruits ) # True
4 print ( " grape " in fruits ) # False
5 print ( " grape " not in fruits ) # True
6
7 # Works on strings too
8 name = " Ravi Kumar "
9 print ( " Ravi " in name ) # True
10 print ( " x " in name ) # False
11
Prepared for Classroom Use 16 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
12 # Works on tuples
13 numbers = (1 , 2 , 3 , 4 , 5)
14 print (3 in numbers ) # True
15 print (10 not in numbers ) # True
6 Python Data Structures: Tuples and Lists
6.1 Tuples
6.1.1 What is a Tuple?
A tuple is an ordered collection of items that is immutable (cannot be changed after
creation). Think of a tuple like a fixed record – once you create it, you cannot modify it.
Analogy: A tuple is like the date of birth printed on your ID card – it is fixed and cannot
be changed.
Syntax: my tuple = (item1, item2, item3)
Example 1: Creating and Accessing Tuples
1 # Creating tuples
2 student = ( " Alice " , 20 , " CSE " , 8.5)
3 coords = (10 , 20)
4 single = (42 ,) # note : need comma for single - element
tuple
5
6 # Accessing elements ( index starts at 0)
7 print ( student [0]) # Alice ( first element )
8 print ( student [1]) # 20
9 print ( student [ -1]) # 8.5 ( last element using negative index
)
10
11 # Tuple length
12 print ( len ( student ) ) # 4
13
14 # Tuple unpacking
15 name , age , branch , cgpa = student
16 print ( name , age ) # Alice 20
6.1.2 Unpacking Sequences
Unpacking means assigning values from a tuple (or any sequence) directly to individual
variables in one line.
Example 2: Unpacking Sequences
1 # Basic unpacking
2 point = (3 , 7)
Prepared for Classroom Use 17 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
3 x , y = point
4 print ( " x = " , x , " y = " , y ) # x = 3 y = 7
5
6 # Swapping variables using tuple unpacking
7 a = 10
8 b = 20
9 a, b = b, a # swap without temp variable
10 print (a , b ) # 20 10
11
12 # Extended unpacking using *
13 numbers = (1 , 2 , 3 , 4 , 5)
14 first , * middle , last = numbers
15 print ( first ) # 1
16 print ( middle ) # [2 , 3 , 4]
17 print ( last ) # 5
6.1.3 Tuple Operations
Example 3: Tuple Operations
1 t1 = (1 , 2 , 3)
2 t2 = (4 , 5 , 6)
3
4 # Concatenation
5 t3 = t1 + t2
6 print ( t3 ) # (1 , 2 , 3 , 4 , 5 , 6)
7
8 # Repetition
9 t4 = t1 * 3
10 print ( t4 ) # (1 , 2 , 3 , 1 , 2 , 3 , 1 , 2 , 3)
11
12 # Membership
13 print (2 in t1 ) # True
14
15 # Slicing
16 print ( t3 [1:4]) # (2 , 3 , 4)
17
18 # Count and Index
19 t = (1 , 2 , 2 , 3 , 2)
20 print ( t . count (2) ) # 3 ( how many times 2 appears )
21 print ( t . index (3) ) # 3 ( position of value 3)
6.2 Lists
6.2.1 What is a List?
A list is an ordered collection of items that is mutable (can be changed after creation).
Lists can store items of different data types.
Prepared for Classroom Use 18 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Analogy: A list is like your shopping list – you can add, remove, or change items anytime.
Syntax: my list = [item1, item2, item3]
Example 1: Creating and Accessing Lists
1 # Creating lists
2 fruits = [ " apple " , " banana " , " mango " ]
3 numbers = [10 , 20 , 30 , 40 , 50]
4 mixed = [1 , " hello " , 3.14 , True ] # can mix types
5 empty = []
6
7 # Accessing elements
8 print ( fruits [0]) # apple
9 print ( fruits [ -1]) # mango ( last element )
10 print ( numbers [2]) # 30
11
12 # Modifying elements ( lists are mutable !)
13 fruits [1] = " grapes "
14 print ( fruits ) # [ ’ apple ’, ’ grapes ’, ’ mango ’]
Example 2: List Methods
1 marks = [75 , 88 , 62 , 91 , 55]
2
3 marks . append (79) # add at end
4 print ( marks ) # [75 , 88 , 62 , 91 , 55 , 79]
5
6 marks . insert (2 , 100) # insert 100 at index 2
7 print ( marks ) # [75 , 88 , 100 , 62 , 91 , 55 , 79]
8
9 marks . remove (62) # remove first occurrence of 62
10 print ( marks ) # [75 , 88 , 100 , 91 , 55 , 79]
11
12 popped = marks . pop () # removes and returns last element
13 print ( popped ) # 79
14
15 marks . sort () # sort in ascending order
16 print ( marks ) # [55 , 75 , 88 , 91 , 100]
17
18 marks . reverse () # reverse the list
19 print ( marks ) # [100 , 91 , 88 , 75 , 55]
20
21 print ( len ( marks ) ) # 5
22 print ( sum ( marks ) ) # 409
23 print ( max ( marks ) ) # 100
24 print ( min ( marks ) ) # 55
Prepared for Classroom Use 19 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
6.3 Slicing (Lists and Tuples)
Slicing allows you to extract a portion of a list or tuple.
Syntax: sequence[start : stop : step]
start – index to begin (inclusive). Default = 0
stop – index to end (exclusive). Default = end
step – how many to skip. Default = 1
Example: Slicing
1 numbers = [10 , 20 , 30 , 40 , 50 , 60 , 70]
2 # index : 0 1 2 3 4 5 6
3
4 print ( numbers [1:4]) # [20 , 30 , 40] ( index 1 to 3)
5 print ( numbers [:3]) # [10 , 20 , 30] ( from start to index
2)
6 print ( numbers [4:]) # [50 , 60 , 70] ( from index 4 to end )
7 print ( numbers [::2]) # [10 , 30 , 50 , 70] ( every 2 nd
element )
8 print ( numbers [:: -1]) # [70 , 60 , 50 , 40 , 30 , 20 , 10] (
reversed )
9 print ( numbers [1:6:2]) # [20 , 40 , 60]
Common Errors with Lists and Tuples
t = (42) is NOT a tuple – it is just the integer 42! Use t = (42,) with a
comma.
Trying to modify a tuple: t[0] = 5 gives TypeError: ’tuple’ object does
not support item assignment
Index out of range: my list[10] when list has only 5 elements gives IndexError
7 Loops in Python
7.1 Introduction to Loops
Loops are used to execute a block of code repeatedly. Without loops, you would have to
write the same code over and over.
Analogy: Imagine you need to write “I will study Python” 100 times. Instead of writing
it 100 times, you use a loop!
7.2 The while Loop
A while loop runs as long as a given condition is True.
Syntax:
1 while condition :
2 # code to repeat
Prepared for Classroom Use 20 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Example 1: while loop – Counting
1 count = 1
2
3 while count <= 5:
4 print ( " Count : " , count )
5 count = count + 1 # or count += 1
6
7 print ( " Loop finished ! " )
8
9 # Output :
10 # Count : 1
11 # Count : 2
12 # Count : 3
13 # Count : 4
14 # Count : 5
15 # Loop finished !
Example 2: while loop – Sum of numbers
1 n = int ( input ( " Enter a number : " ) )
2 total = 0
3 i = 1
4
5 while i <= n :
6 total = total + i
7 i += 1
8
9 print ( " Sum of 1 to " , n , " is : " , total )
10 # If n =5 , output : Sum of 1 to 5 is : 15
7.3 The for Loop
A for loop is used to iterate over a sequence (list, tuple, string, range, etc.).
Syntax:
1 for variable in sequence :
2 # code to repeat
Example 1: for loop with range()
1 # range ( start , stop , step )
2 for i in range (1 , 6) : # 1, 2, 3, 4, 5
3 print ( " Number : " , i )
4
5 # range with step
Prepared for Classroom Use 21 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
6 for i in range (0 , 11 , 2) : # 0 , 2 , 4 , 6 , 8 , 10
7 print (i , end = " " ) # end =" " prints on same line
8
9 # Reverse range
10 for i in range (5 , 0 , -1) : # 5, 4, 3, 2, 1
11 print ( i )
Example 2: for loop over a list
1 fruits = [ " apple " , " banana " , " mango " , " orange " ]
2
3 for fruit in fruits :
4 print ( " Fruit : " , fruit )
5
6 # With index using enumerate ()
7 for index , fruit in enumerate ( fruits ) :
8 print ( index , " ->" , fruit )
9
10 # Output :
11 # 0 -> apple
12 # 1 -> banana
13 # 2 -> mango
14 # 3 -> orange
Example 3: for loop over a string
1 name = " Python "
2
3 for char in name :
4 print ( char )
5
6 # Output :
7 # P
8 # y
9 # t
10 # h
11 # o
12 # n
7.4 Nested Loops
A nested loop is a loop inside another loop. The inner loop completes all its iterations
for each iteration of the outer loop.
Prepared for Classroom Use 22 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Example: Multiplication Table using Nested Loops
1 for i in range (1 , 4) : # outer loop : rows
2 for j in range (1 , 4) : # inner loop : columns
3 print ( i * j , end = " \ t " ) # \ t adds tab space
4 print () # newline after each row
5
6 # Output :
7 # 1 2 3
8 # 2 4 6
9 # 3 6 9
7.5 break and continue Statements
Example: break – Exit the loop early
1 # Stop searching when item is found
2 numbers = [10 , 25 , 33 , 42 , 55 , 60]
3
4 search = 42
5 for num in numbers :
6 if num == search :
7 print ( " Found " , search , " ! " )
8 break # exit the loop immediately
9 print ( " Checking : " , num )
10
11 # Output :
12 # Checking : 10
13 # Checking : 25
14 # Checking : 33
15 # Found 42 !
Example: continue – Skip an iteration
1 # Print all numbers from 1 -10 except multiples of 3
2 for i in range (1 , 11) :
3 if i % 3 == 0:
4 continue # skip this iteration
5 print (i , end = " " )
6
7 # Output : 1 2 4 5 7 8 10
Common Loop Errors
Infinite Loop: Forgetting to update the counter in a while loop: while x >
0: print(x) never stops!
Off-by-one Error: Using range(1, 5) gives 1,2,3,4 (NOT 5). The stop value
Prepared for Classroom Use 23 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
is excluded.
Modifying list while iterating: Never add or remove items from a list inside
a for loop iterating over it.
8 Bitwise Operators
8.1 Introduction
Bitwise operators work directly on the binary (bit-level) representation of integers.
They are used in low-level programming, networking, and encryption.
Operator Description Example Result
& Bitwise AND 5 & 3 1
— Bitwise OR 5 | 3 7
ˆ Bitwise XOR 5 ^ 3 6
˜ Bitwise NOT ~5 -6
¡¡ Left Shift 5 << 1 10
¿¿ Right Shift 5 >> 1 2
Example: Bitwise Operators
1 a = 5 # binary : 0101
2 b = 3 # binary : 0011
3
4 print ( " AND : " , a & b ) # 0001 = 1
5 print ( " OR : " , a | b ) # 0111 = 7
6 print ( " XOR : " , a ^ b ) # 0110 = 6
7 print ( " NOT : " , ~ a ) # -(5+1) = -6
8 print ( " Left Shift : " , a << 1) # 1010 = 10 ( multiply by 2)
9 print ( " Right Shift : " , a >> 1) # 0010 = 2 ( divide by 2)
9 Mutable and Immutable Sequences
9.1 Explanation
Type Mutable (Can Change) Immutable (Cannot
Change)
Examples list, dict, set int, float, str, tuple
Can modify? Yes No
Memory New location not needed New object created on
change
Prepared for Classroom Use 24 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Example: Mutable vs Immutable
1 # List is MUTABLE
2 my_list = [1 , 2 , 3]
3 my_list [0] = 99 # OK - lists can be modified
4 print ( my_list ) # [99 , 2 , 3]
5
6 # Tuple is IMMUTABLE
7 my_tuple = (1 , 2 , 3)
8 # my_tuple [0] = 99 # TypeError ! tuples cannot be modified
9
10 # String is IMMUTABLE
11 name = " Python "
12 # name [0] = " J " # TypeError !
13 name = " Jython " # This creates a NEW string object
9.2 List Comprehension
List Comprehension is a short, elegant way to create a new list by applying an expres-
sion to each item in a sequence.
Syntax: new list = [expression for item in sequence if condition]
Example 1: List Comprehension vs Normal Loop
1 # Normal way (5 lines )
2 squares = []
3 for i in range (1 , 6) :
4 squares . append ( i ** 2)
5 print ( squares ) # [1 , 4 , 9 , 16 , 25]
6
7 # List Comprehension way (1 line )
8 squares = [ i ** 2 for i in range (1 , 6) ]
9 print ( squares ) # [1 , 4 , 9 , 16 , 25]
10
11 # With condition : only even numbers squared
12 even_squares = [ i **2 for i in range (1 , 11) if i % 2 == 0]
13 print ( even_squares ) # [4 , 16 , 36 , 64 , 100]
Example 2: Practical List Comprehension
1 # Convert all names to uppercase
2 names = [ " alice " , " bob " , " charlie " , " diana " ]
3 upper_names = [ name . upper () for name in names ]
4 print ( upper_names ) # [ ’ ALICE ’, ’ BOB ’, ’ CHARLIE ’, ’ DIANA ’]
5
6 # Filter only passing marks
7 marks = [45 , 32 , 78 , 55 , 20 , 90 , 38]
8 passing = [ m for m in marks if m >= 40]
Prepared for Classroom Use 25 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
9 print ( passing ) # [45 , 78 , 55 , 90]
10 Sets
10.1 Introduction
A set is an unordered collection of unique items. Sets automatically remove duplicates.
Analogy: Like a bag of marbles where each colour appears only once – no duplicates
allowed!
Key Properties:
Unordered (no index)
No duplicate elements
Mutable (you can add/remove items)
Cannot contain mutable items like lists
Example 1: Creating Sets
1 # Creating sets
2 fruits = { " apple " , " banana " , " mango " , " apple " } # duplicate
removed
3 print ( fruits ) # { ’ apple ’, ’ banana ’, ’ mango ’} - order may
vary
4
5 numbers = set ([1 , 2 , 3 , 3 , 4 , 4 , 5]) # from list
6 print ( numbers ) # {1 , 2 , 3 , 4 , 5}
7
8 # Adding and removing
9 fruits . add ( " orange " )
10 fruits . remove ( " banana " )
11 print ( fruits )
12
13 # Check membership
14 print ( " mango " in fruits ) # True
Prepared for Classroom Use 26 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
10.2 Set Operations
Operation Symbol / Method Description
Union | or .union() All elements from both sets
Intersection & or Common elements only
.intersection()
Difference - or .difference() Elements in first but not
second
Symmetric ^ or Elements in one but not
Diff both
.symmetric difference()
Subset <= or .issubset() Is one set inside another?
Example 2: Set Operations
1 A = {1 , 2 , 3 , 4 , 5}
2 B = {4 , 5 , 6 , 7 , 8}
3
4 print ( " Union : " , A | B ) # {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8}
5 print ( " Intersection : " , A & B ) # {4 , 5}
6 print ( " Difference (A - B ) : " , A - B ) # {1 , 2 , 3}
7 print ( " Sym Difference : " , A ^ B ) # {1 , 2 , 3 , 6 , 7 , 8}
8
9 # Subset and Superset
10 C = {1 , 2 , 3}
11 print ( C . issubset ( A ) ) # True ( C is inside A )
12 print ( A . issuperset ( C ) ) # True
Example 3: Real-world Application of Sets
1 # Find students enrolled in both courses
2 python_students = { " Alice " , " Bob " , " Charlie " , " Diana " }
3 java_students = { " Bob " , " Diana " , " Eve " , " Frank " }
4
5 # Students in both courses
6 both = python_students & java_students
7 print ( " Both courses : " , both ) # { ’ Bob ’, ’ Diana ’}
8
9 # Students in only Python
10 only_python = python_students - java_students
11 print ( " Only Python : " , only_python ) # { ’ Alice ’, ’ Charlie ’}
12
13 # All students ( union )
14 all_students = python_students | java_students
15 print ( " All students : " , all_students )
Prepared for Classroom Use 27 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
11 Dictionaries
11.1 What is a Dictionary?
A dictionary stores data as key-value pairs. Each key is unique and is used to access
its corresponding value.
Analogy: A dictionary is like a real-world dictionary – you look up a word (key) and get
its meaning (value).
Syntax: my dict = {key1: value1, key2: value2}
Example 1: Creating and Accessing Dictionaries
1 student = {
2 " name " : " Alice " ,
3 " age " : 20 ,
4 " branch " : " CSE " ,
5 " cgpa " : 8.5
6 }
7
8 # Accessing values
9 print ( student [ " name " ]) # Alice
10 print ( student . get ( " age " ) ) # 20
11 print ( student . get ( " phone " , " N / A " ) ) # N / A ( default if not
found )
12
13 # Modifying values
14 student [ " cgpa " ] = 9.0
15 student [ " email " ] = " alice@gmail . com " # add new key
16
17 # Delete a key
18 del student [ " age " ]
19
20 print ( student )
Example 2: Iterating over Dictionary
1 marks = { " Maths " : 88 , " Physics " : 75 , " Chemistry " : 91 , "
English " : 82}
2
3 # Iterate over keys
4 for subject in marks :
5 print ( subject )
6
7 # Iterate over values
8 for score in marks . values () :
9 print ( score )
10
11 # Iterate over key - value pairs
12 for subject , score in marks . items () :
Prepared for Classroom Use 28 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
13 print ( f " { subject }: { score } " )
14
15 # Dictionary methods
16 print ( marks . keys () ) # all keys
17 print ( marks . values () ) # all values
18 print ( len ( marks ) ) # number of entries
11.2 Nested Dictionaries
A nested dictionary is a dictionary that contains other dictionaries as values.
Example: Nested Dictionaries
1 students = {
2 " S001 " : { " name " : " Alice " , " marks " : 88 , " grade " : " A " } ,
3 " S002 " : { " name " : " Bob " , " marks " : 72 , " grade " : " B " } ,
4 " S003 " : { " name " : " Charlie " , " marks " : 55 , " grade " : " C " }
5 }
6
7 # Access nested values
8 print ( students [ " S001 " ][ " name " ]) # Alice
9 print ( students [ " S002 " ][ " marks " ]) # 72
10
11 # Add a new student
12 students [ " S004 " ] = { " name " : " Diana " , " marks " : 95 , " grade " : "
A+"}
13
14 # Iterate nested dictionary
15 for roll , info in students . items () :
16 print ( f " { roll }: { info [ ’ name ’]} -> { info [ ’ grade ’]} " )
11.3 Working with Multiple Data Structures
Example: Combining Lists, Tuples, Sets, Dicts
1 # A list of dictionaries ( student records )
2 class_data = [
3 { " name " : " Alice " , " marks " : [88 , 76 , 91]} ,
4 { " name " : " Bob " , " marks " : [65 , 72 , 80]} ,
5 { " name " : " Charlie " , " marks " : [55 , 60 , 70]} ,
6 ]
7
8 # Calculate average for each student
9 for student in class_data :
10 avg = sum ( student [ " marks " ]) / len ( student [ " marks " ])
11 print ( f " { student [ ’ name ’]}: Average = { avg :.2 f } " )
12
Prepared for Classroom Use 29 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
13 # Using set to find unique subjects
14 all_marks = [ m for s in class_data for m in s [ " marks " ]]
15 print ( " All marks ( unique ) : " , set ( all_marks ) )
12 Strings
12.1 Introduction
A string is a sequence of characters enclosed in single, double, or triple quotes.
Examples: "Hello", ’Python’, """Multi-line string"""
12.2 String Length, Concatenation and Repetition
Example 1: Basic String Operations
1 s1 = " Hello "
2 s2 = " World "
3
4 # Length
5 print ( len ( s1 ) ) # 5
6
7 # Concatenation ( joining strings )
8 s3 = s1 + " " + s2
9 print ( s3 ) # Hello World
10
11 # Repetition
12 s4 = " Python ! " * 3
13 print ( s4 ) # Python ! Python ! Python !
14
15 # Check membership
16 print ( " ello " in s1 ) # True
17 print ( " xyz " in s1 ) # False
12.3 Indexing and Slicing of Strings
Example 2: String Indexing and Slicing
1 name = " Python "
2 # index : 0 1 2 3 4 5
3 # - ve : -6 -5 -4 -3 -2 -1
4
5 # Indexing
6 print ( name [0]) # P
7 print ( name [ -1]) # n ( last character )
8
9 # Slicing
Prepared for Classroom Use 30 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
10 print ( name [1:4]) # yth
11 print ( name [:3]) # Pyt
12 print ( name [3:]) # hon
13 print ( name [:: -1]) # nohtyP ( reversed string )
14 print ( name [::2]) # Pto ( every 2 nd character )
12.4 Built-in String Functions
Example 3: Common String Methods
1 text = " Hello , Python World ! "
2
3 print ( text . upper () ) # " HELLO , PYTHON WORLD ! "
4 print ( text . lower () ) # " hello , python world ! "
5 print ( text . strip () ) # " Hello , Python World !" (
removes spaces )
6 print ( text . lstrip () ) # removes left spaces
7 print ( text . rstrip () ) # removes right spaces
8 print ( text . replace ( " Python " , " Beautiful " ) ) # replaces word
9 print ( text . find ( " Python " ) ) # 9 ( index where word starts )
10 print ( text . count ( " l " ) ) # 3 ( how many times ’l ’ appears )
11 print ( text . split ( " ," ) ) # [ ’ Hello ’, ’ Python World !
’]
12 print ( text . startswith ( " Hello " ) ) # True
13 print ( text . endswith ( " ! " ) ) # True
14
15 # String formatting
16 name = " Alice "
17 age = 20
18 print ( f " My name is { name } and I am { age } years old . " )
19 print ( " My name is {} and I am {} years old . " . format ( name ,
age ) )
Prepared for Classroom Use 31 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Method Description
upper() Converts to uppercase
lower() Converts to lowercase
strip() Removes leading/trailing whitespace
replace(a, b) Replaces all occurrences of a with b
split(sep) Splits string by separator, returns list
join(list) Joins list items into a string
find(sub) Returns index of first occurrence (-1 if not
found)
count(sub) Counts how many times substring appears
startswith(s) Returns True if string starts with s
endswith(s) Returns True if string ends with s
isdigit() Returns True if all characters are digits
isalpha() Returns True if all characters are letters
13 Functions
13.1 What is a Function?
A function is a reusable block of code that performs a specific task. Instead of writing
the same code multiple times, you write a function once and call it whenever needed.
Analogy: A function is like a recipe. You write the recipe once and use it whenever you
want to cook that dish!
13.2 Parts of a Function
1 def function_name ( parameters ) :
2 """ Docstring - describes the function """
3 # function body
4 return result
def – keyword to define a function
function name – name you give to the function
parameters – inputs the function accepts
docstring – optional description
return – sends back a result
Example 1: Simple Function
1 # Define the function
2 def greet ( name ) :
3 """ This function greets a person . """
4 message = " Hello , " + name + " ! Welcome to Python . "
5 return message
6
7 # Call the function
Prepared for Classroom Use 32 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
8 result = greet ( " Alice " )
9 print ( result ) # Hello , Alice ! Welcome to Python .
10
11 print ( greet ( " Bob " ) ) # Hello , Bob ! Welcome to Python .
Example 2: Function with Multiple Parameters
1 def calculate_area ( length , width ) :
2 """ Calculate area of a rectangle . """
3 area = length * width
4 return area
5
6 # Call the function
7 a1 = calculate_area (5 , 3)
8 a2 = calculate_area (10 , 7)
9 print ( " Area 1: " , a1 ) # 15
10 print ( " Area 2: " , a2 ) # 70
13.3 Keyword and Default Arguments
Example 3: Default and Keyword Arguments
1 # Default argument : if not provided , use default value
2 def introduce ( name , age =18 , city = " Unknown " ) :
3 print ( f " Name : { name } , Age : { age } , City : { city } " )
4
5 introduce ( " Alice " , 22 , " Delhi " ) # all provided
6 introduce ( " Bob " , 25) # city uses default
7 introduce ( " Charlie " ) # age and city use
defaults
8
9 # Keyword arguments : specify by name ( order doesn ’t matter )
10 introduce ( city = " Mumbai " , name = " Diana " , age =30)
13.4 Scope Rules
Scope refers to where a variable is accessible in your program.
Example 4: Local vs Global Scope
1 x = 100 # global variable
2
3 def my_func () :
4 y = 50 # local variable ( only inside this function )
5 print ( " Inside function , x = " , x ) # can access global x
6 print ( " Inside function , y = " , y )
Prepared for Classroom Use 33 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
8 my_func ()
9 print ( " Outside function , x = " , x )
10 # print ( y ) # NameError ! y is not accessible outside
11
12 # Using global keyword to modify global variable
13 def change_x () :
14 global x
15 x = 999
16
17 change_x ()
18 print ( " After change_x , x = " , x ) # 999
13.5 Lambda Function
A lambda function is a small, anonymous (no name) function defined in a single line.
Syntax: lambda arguments : expression
Example: Lambda Functions
1 # Normal function
2 def square ( x ) :
3 return x ** 2
4
5 # Equivalent lambda function
6 square_lambda = lambda x : x ** 2
7
8 print ( square (5) ) # 25
9 print ( square_lambda (5) ) # 25
10
11 # Lambda with multiple arguments
12 add = lambda a , b : a + b
13 print ( add (3 , 7) ) # 10
14
15 # Lambda in sort -- sort by second element
16 pairs = [(1 , ’b ’) , (3 , ’a ’) , (2 , ’c ’) ]
17 pairs . sort ( key = lambda pair : pair [1])
18 print ( pairs ) # [(3 , ’a ’) , (1 , ’b ’) , (2 , ’c ’) ]
19
20 # Lambda with filter
21 numbers = [1 , 2 , 3 , 4 , 5 , 6 , 7 , 8]
22 evens = list ( filter ( lambda x : x % 2 == 0 , numbers ) )
23 print ( evens ) # [2 , 4 , 6 , 8]
Prepared for Classroom Use 34 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
Common Function Errors
Calling a function before defining it – always define before calling!
Forgetting to return a value when the caller expects one
Too many or too few arguments when calling a function
Using a local variable outside the function – causes NameError
14 File Handling
14.1 Introduction
File handling allows Python programs to read data from files and write data to files
stored on the hard disk.
Analogy: Files are like notebooks. Reading a file is like opening a notebook and reading
it. Writing to a file is like writing in a notebook.
14.2 File Modes
Mode Description File Exists?
r Read only (default). Error if file not Must exist
found.
w Write. Creates new file or overwrites Creates if
existing. needed
a Append. Adds to end of file. Creates if
needed
r+ Read and write. Must exist
rb / wb Read/Write in binary mode –
14.3 Reading and Writing Text Files
Example 1: Writing to a File
1 # Writing to a file ( creates file if it does not exist )
2 file = open ( " students . txt " , " w " ) # ’w ’ mode
3
4 file . write ( " Alice \ n " )
5 file . write ( " Bob \ n " )
6 file . write ( " Charlie \ n " )
7
8 file . close () # always close the file !
9 print ( " File written successfully . " )
Example 2: Reading from a File
1 # Reading entire file content
2 file = open ( " students . txt " , " r " )
Prepared for Classroom Use 35 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
3 content = file . read ()
4 print ( content )
5 file . close ()
6
7 # Reading line by line
8 file = open ( " students . txt " , " r " )
9 for line in file :
10 print ( line . strip () ) # strip () removes trailing \ n
11 file . close ()
12
13 # Using with statement ( auto - closes file )
14 with open ( " students . txt " , " r " ) as file :
15 lines = file . readlines () # returns list of lines
16 for line in lines :
17 print ( line . strip () )
14.4 Appending to Files
Example 3: Appending to a File
1 # Appending -- adds to end without deleting existing content
2 with open ( " students . txt " , " a " ) as file :
3 file . write ( " Diana \ n " )
4 file . write ( " Eve \ n " )
5
6 # Verify the content
7 with open ( " students . txt " , " r " ) as file :
8 print ( file . read () )
9
10 # Output will now include Alice , Bob , Charlie , Diana , Eve
14.5 Working with CSV Files
A CSV (Comma Separated Values) file stores data in a tabular format with values
separated by commas.
Example 4: Writing a CSV File
1 import csv
2
3 # Writing CSV data
4 students = [
5 [ " Name " , " Age " , " Marks " ] ,
6 [ " Alice " , 20 , 88] ,
7 [ " Bob " , 21 , 75] ,
8 [ " Charlie " , 19 , 91]
9 ]
Prepared for Classroom Use 36 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
10
11 with open ( " students . csv " , " w " , newline = " " ) as file :
12 writer = csv . writer ( file )
13 writer . writerows ( students )
14
15 print ( " CSV file created ! " )
Example 5: Reading a CSV File
1 import csv
2
3 with open ( " students . csv " , " r " ) as file :
4 reader = csv . reader ( file )
5 for row in reader :
6 print ( row )
7
8 # Output :
9 # [ ’ Name ’, ’ Age ’, ’ Marks ’]
10 # [ ’ Alice ’, ’20 ’ , ’88 ’]
11 # [ ’ Bob ’, ’21 ’ , ’75 ’]
12 # [ ’ Charlie ’, ’19 ’ , ’91 ’]
13
14 # Using DictReader ( reads each row as a dictionary )
15 with open ( " students . csv " , " r " ) as file :
16 reader = csv . DictReader ( file )
17 for row in reader :
18 print ( row [ " Name " ] , " ->" , row [ " Marks " ])
Common File Handling Errors
FileNotFoundError – File does not exist when using "r" mode. Always check
file path.
Forgetting to close the file – Always use with open(...) as f: to auto-close.
Opening in "w" mode when you want to append – "w" mode DELETES existing
content!
Not adding newline="" when writing CSV on Windows – causes blank lines.
15 Quick Revision Summary
COMPLETE SUMMARY – Python Programming
1. Programming Languages
High-level (Python, Java) – easy, human-readable. Low-level (Assembly) – close
to hardware. Compiler: translates all at once. Interpreter: translates line by line.
Python uses Interpreter.
Prepared for Classroom Use 37 Dept. of Computer Science
Python Programming Notes [Link] – Beginner Level
2. Operators
Arithmetic: + - * / // % ** — Relational: == != > < >= <= — Logical: and or
not
Bitwise: & | ^ ~ << >> — Identity: is, is not — Membership: in, not in
3. Conditional Statements
if → elif → else — Nested if for complex conditions — Python uses indentation
for blocks
4. Variables & Memory
Variables are names pointing to objects. Garbage Collection frees unused memory
automatically.
5. Loops
while – runs while condition is True — for – iterates over sequences
break – exits loop — continue – skips current iteration — Nested loops for 2D
patterns
6. Data Structures
List [] – ordered, mutable — Tuple () – ordered, immutable
Set {} – unordered, unique items — Dict {} – key:value pairs
Slicing: seq[start:stop:step] — List Comprehension: [expr for x in seq if
cond]
7. Strings
Immutable sequence of characters. Methods: upper(), lower(), strip(),
split(), replace(), find()
f-strings: f"Hello {name}" — Slicing works same as lists
8. Functions
def to define, return to send back value. Default args: def f(x, y=10)
Lambda: lambda x: x**2 — Scope: local vs global — global keyword to modify
global var
9. File Handling
"r" read — "w" write (overwrites) — "a" append
Always use with open() as f: — CSV module for tabular data
Best of Luck with Your Python Journey!
Practice every day – Programming is a skill you learn by doing.
Prepared for Classroom Use 38 Dept. of Computer Science