0% found this document useful (0 votes)
11 views77 pages

OOP Programing With Python

This document serves as a comprehensive guide to programming with Python, covering its introduction, features, applications, and installation. It includes detailed chapters on Python basics, syntax, data structures, functions, and object-oriented programming, along with practical exercises and best practices. The document is structured into multiple parts, providing a thorough understanding of Python for both beginners and advanced users.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views77 pages

OOP Programing With Python

This document serves as a comprehensive guide to programming with Python, covering its introduction, features, applications, and installation. It includes detailed chapters on Python basics, syntax, data structures, functions, and object-oriented programming, along with practical exercises and best practices. The document is structured into multiple parts, providing a thorough understanding of Python for both beginners and advanced users.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

By

W3SKILLSET | Abid Maqsood

WhatsApp : +923419463442
Part 1: Introduction to Programming with Python.......................................................................... 4
Chapter 1: Introduction to Python Programming..................................................................... 5
1.1. What is Python?..........................................................................................................5
1.2. History of Python.........................................................................................................5
1.3. Features of Python......................................................................................................6
1.3.1. Easy to Learn.....................................................................................................6
1.3.2. Interpreted Language.........................................................................................6
1.3.3. Dynamically Typed.............................................................................................6
1.3.4. Object-Oriented..................................................................................................6
1.3.5. Large Standard Library...................................................................................... 7
1.4. Applications of Python................................................................................................ 8
1.4.1. Web Development..............................................................................................8
1.4.2. Data Analysis & Visualization.............................................................................9
1.4.3. Artificial Intelligence & Machine Learning.......................................................... 9
1.4.4. Automation & Scripting.................................................................................... 10
1.5. Installing Python........................................................................................................11
1.6. Python IDEs (Development Environments)...............................................................11
1.6.1. VS Code (Recommended)............................................................................... 11
1.6.2. PyCharm.......................................................................................................... 12
1.6.3. Jupyter Notebook.............................................................................................13
1.7. Writing Your First Python Program............................................................................14
1.8. Common Beginner Mistakes.....................................................................................14
1.9. Summary...................................................................................................................15
Practice Exercises........................................................................................................... 15
Part 2: Python Basics (Core Concepts)....................................................................................... 16
Chapter 2: Python Syntax and Basics................................................................................... 17
2.1. Python Syntax...........................................................................................................17
2.2. Python Keywords...................................................................................................... 17
2.3. Comments in Python.................................................................................................18
2.4. Variables in Python................................................................................................... 19
2.5. Data Types in Python................................................................................................19
2.6. Type Casting............................................................................................................. 21
2.7. Input Function........................................................................................................... 21
2.8. Output Function (print())............................................................................................22
2.9. Common Beginner Errors......................................................................................... 23
2.10. Summary.................................................................................................................23
Practice Exercises........................................................................................................... 23
Chapter 3: Operators in Python............................................................................................. 24
3.1. What are Operators?................................................................................................ 24
3.2. Arithmetic Operators................................................................................................. 25

1
3.3. Relational (Comparison) Operators.......................................................................... 26
3.4. Logical Operators......................................................................................................27
3.5. Assignment Operators.............................................................................................. 28
3.6. Membership Operators............................................................................................. 28
3.7. Identity Operators..................................................................................................... 29
3.8. Operator Precedence................................................................................................30
3.9. Common Beginner Mistakes.....................................................................................30
3.10. Summary.................................................................................................................30
Practice Exercises........................................................................................................... 31
Chapter 4: Control Flow Statements in Python......................................................................32
4.1. What are Control Flow Statements?......................................................................... 32
4.2. Conditional Statements (if, elif, else)........................................................................ 32
4.3. Nested Conditions.....................................................................................................34
4.4. Looping in Python..................................................................................................... 35
4.5. for Loop.....................................................................................................................35
4.6. while Loop.................................................................................................................36
4.7. Loop Control Statements.......................................................................................... 36
4.8. Practical Examples................................................................................................... 38
4.9. Common Beginner Mistakes.....................................................................................39
4.10. Summary.................................................................................................................40
Practice Exercises........................................................................................................... 40
Part 3: Data Structures in Python................................................................................................ 41
Chapter 5: Strings in Python..................................................................................................42
5.1. What is a String?.......................................................................................................42
5.2. Accessing Characters (Indexing).............................................................................. 42
5.3. String Slicing............................................................................................................. 43
5.4. String Length.............................................................................................................44
5.5. Common String Methods.......................................................................................... 44
5.6. Checking String Content........................................................................................... 46
5.7. Formatting Strings.....................................................................................................47
5.8. Real-World Examples............................................................................................... 47
5.9. Common Beginner Mistakes.....................................................................................49
5.10. Summary.................................................................................................................49
Practice Exercises........................................................................................................... 50
Chapter 6: Lists in Python......................................................................................................51
6.1. What is a List?.......................................................................................................... 51
6.2. Creating Lists............................................................................................................ 51
6.3. List Indexing..............................................................................................................52
6.4. List Slicing.................................................................................................................53
6.5. Updating List Items................................................................................................... 54
6.6. Common List Methods.............................................................................................. 54

2
6.7. Looping Through a List............................................................................................. 55
6.8. List Comprehensions................................................................................................ 56
6.9. Nested Lists.............................................................................................................. 56
6.10. Real-World Examples............................................................................................. 57
6.11. Common Beginner Mistakes................................................................................... 58
6.12. Summary.................................................................................................................59
Practice Exercises........................................................................................................... 59
Chapter 7: Tuples and Sets in Python................................................................................... 60
Part A: Tuples in Python.................................................................................................. 60
7.1. What is a Tuple?....................................................................................................... 60
7.2. Tuple Immutability..................................................................................................... 60
7.3. Creating Tuples.........................................................................................................61
7.4. Tuple Indexing and Slicing........................................................................................ 61
7.5. Tuple Operations...................................................................................................... 62
7.6. Tuple Methods.......................................................................................................... 62
7.7. Tuple Unpacking....................................................................................................... 63
Part B: Sets in Python......................................................................................................63
7.8. What is a Set?...........................................................................................................63
7.9. Creating Sets............................................................................................................ 64
7.10. Set Properties......................................................................................................... 64
7.11. Set Methods............................................................................................................ 64
7.12. Set Operations........................................................................................................ 65
7.13. Use Cases of Sets (Real-World Examples)............................................................ 66
7.14. Tuple vs List vs Set (Quick Comparison)................................................................ 67
7.15. Common Beginner Mistakes...................................................................................67
7.16. Summary.................................................................................................................68
Practice Exercises........................................................................................................... 68
Part 4: Functions and Modules.................................................................................................... 69
Chapter 8: Dictionaries in Python.......................................................................................... 70
Chapter 9: Functions in Python............................................................................................. 76
Chapter 10: Modules and Packages in Python......................................................................81
Part 5: File Handling and Error Management.............................................................................. 86
Chapter 11: File Handling in Python...................................................................................... 87
Chapter 12: Exception Handling in Python............................................................................ 93
Part 6: Object-Oriented Programming (OOP)..............................................................................98
Chapter 13: Introduction to Object-Oriented Programming (OOP) in Python........................99
Chapter 14: Core OOP Concepts in Python........................................................................ 105
Chapter 15: Advanced OOP Concepts in Python................................................................ 111
Part 7: Practical Python Applications......................................................................................... 117
Chapter 16: Mini Projects (Beginner) in Python................................................................... 118
Chapter 17: Mini Projects (OOP-Based) in Python..............................................................123

3
Part 8: Best Practices and Next Steps.......................................................................................127
Chapter 18: Python Best Practices......................................................................................128
Chapter 19: Python for Career Growth.................................................................................... 0
Part 9: Appendices........................................................................................................................ 0
Appendix A: Python Keywords List..........................................................................................0
Appendix B: Python Built-in Functions Reference................................................................... 0
Appendix C: Practice Exercises & Solutions........................................................................... 0
Final Note...................................................................................................................................... 0

4
Part 1: Introduction to Programming with Python

5
Chapter 1: Introduction to Python Programming
This chapter introduces Python from zero level, explaining what Python is, why it is popular,
how it evolved, and how to start writing your first Python program.

1.1. What is Python?


Python is a high-level, interpreted, general-purpose programming language that is easy to
read and write. It focuses on simplicity and productivity, which makes it ideal for beginners as
well as professionals.

Key Points:

●​ Human-readable syntax
●​ Less code, more work
●​ Open-source and free
●​ Cross-platform (Windows, macOS, Linux)

Example: Python vs Other Languages

print("Hello, World!")

📌 Only one line is needed to print output.

1.2. History of Python


Python was created by Guido van Rossum and first released in 1991.

Timeline:

●​ 1989: Python development started


●​ 1991: Python 1.0 released
●​ 2000: Python 2.0
●​ 2010: Python 3.0 (major upgrade)

6
●​ Present: Python 3.x (actively maintained)

📌 Python is named after the TV show Monty Python’s Flying Circus, not the snake.

1.3. Features of Python

1.3.1. Easy to Learn

Python syntax is close to English.

if 10 > 5:

print("True")

1.3.2. Interpreted Language

Python executes code line by line, which makes debugging easy.

1.3.3. Dynamically Typed

No need to declare data types.

x = 10

y = "Python"

1.3.4. Object-Oriented

Python supports OOP concepts like classes and objects.

7
1.3.5. Large Standard Library

Python has thousands of built-in modules.

8
1.4. Applications of Python

1.4.1. Web Development

Used in backend development.

Popular frameworks:

●​ Django
●​ Flask
●​ FastAPI

9
1.4.2. Data Analysis & Visualization

Used by data analysts and scientists.

Libraries:

●​ Pandas
●​ NumPy
●​ Matplotlib
●​ Seaborn

1.4.3. Artificial Intelligence & Machine Learning

Python is the #1 language for AI.

Libraries:

●​ TensorFlow
●​ PyTorch
●​ Scikit-learn

10
1.4.4. Automation & Scripting

Python automates repetitive tasks.

Example: Rename files

import os

11
1.5. Installing Python

Step 1: Open Microsoft Store

●​ Search Python
●​ Click on install

Step 3: Verify Installation

python --version

1.6. Python IDEs (Development Environments)

1.6.1. VS Code (Recommended)

●​ Lightweight
●​ Extensions support
●​ Debugging features

12
1.6.2. PyCharm

●​ Powerful IDE
●​ Best for large projects

13
1.6.3. Jupyter Notebook

●​ Best for data science


●​ Code + output together

14
1.7. Writing Your First Python Program

Step 1: Open Editor

Create a file named:

[Link]

Step 2: Write Code

print("Hello, Python!")

Step 3: Run Program

python [Link]

Output:

Hello, Python!

1.8. Common Beginner Mistakes


●​ Forgetting indentation
●​ Misspelling keywords

15
●​ Not saving file before running

1.9. Summary
In this chapter, you learned:

●​ What Python is
●​ Python history
●​ Features and applications
●​ How to install Python
●​ Popular Python IDEs
●​ How to write your first Python program

Practice Exercises
1.​ Print your name using Python
2.​ Check Python version on your system
3.​ Install VS Code and run a Python program

16
Part 2: Python Basics (Core Concepts)

17
Chapter 2: Python Syntax and Basics
This chapter builds the foundation of Python programming. You will learn Python syntax
rules, keywords, comments, variables, data types, type casting, and input/output functions with
clear examples.

2.1. Python Syntax


Python syntax is simple and readable compared to other programming languages. Python
uses indentation instead of brackets {}.

Example: Python Indentation

if 5 > 3:

print("Five is greater than three")

❌ Incorrect indentation causes an error:


if 5 > 3:

print("Error")

2.2. Python Keywords


Keywords are reserved words that have special meaning in Python and cannot be used as
variable names.

18
Common Python Keywords

●​ if, else, elif


●​ for, while, break, continue
●​ True, False, None
●​ class, def, return
●​ import, from, as

Example

# ❌ Invalid
class = 10

# ✅ Valid
my_class = 10

2.3. Comments in Python


Comments are used to explain code and are ignored by Python.

Single-line Comment
# This is a comment
print("Hello")
Multi-line Comment
"""
This is a
multi-line comment
"""

19
📌 Comments improve code readability.

2.4. Variables in Python


A variable is used to store data in memory.

Rules for Variables

●​ Must start with a letter or underscore


●​ Cannot start with a number
●​ Cannot use keywords

Example

name = "Abid"

age = 30

salary = 50000

2.5. Data Types in Python


Python automatically detects data types.

Common Data Types


Data Type Example

int 10

20
float 10.5

str "Python"

bool True

Example

x = 10

price = 99.99

language = "Python"

is_active = True

Check Data Type

print(type(x))

21
2.6. Type Casting
Type casting converts one data type into another.

Types of Casting

●​ int()
●​ float()
●​ str()

Example

x = "10"

y = int(x)

print(y + 5)

❌ Without casting:
print(x + 5) # Error

2.7. Input Function

The input() function is used to take user input.

Example

22
name = input("Enter your name: ")

print("Hello", name)

📌 Input is always received as string.

2.8. Output Function (print())

The print() function displays output.

Example

age = 25

print("Age is", age)

Formatted Output (f-strings)

name = "Ali"

marks = 90

print(f"{name} scored {marks} marks")

23
2.9. Common Beginner Errors
●​ IndentationError
●​ NameError
●​ TypeError

2.10. Summary
In this chapter, you learned:

●​ Python syntax rules


●​ Keywords and comments
●​ Variables and data types
●​ Type casting
●​ Input and output functions

Practice Exercises
1.​ Take user name and age as input and print them
2.​ Convert string number into integer
3.​ Try using a Python keyword as variable (observe error)

24
Chapter 3: Operators in Python
Operators are used to perform operations on variables and values. Python provides different
types of operators to handle mathematical calculations, comparisons, logic building,
assignments, and data checks.

3.1. What are Operators?


Operators are special symbols that perform operations between operands (values or variables).

Example
x = 10 + 5

Here:

●​ + → operator
●​ 10 and 5 → operands

25
3.2. Arithmetic Operators
Arithmetic operators are used for mathematical calculations.

List of Arithmetic Operators


Operator Description Example

+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2.0

% Modulus 10 % 3 = 1

// Floor Division 10 // 3 = 3

** Exponent 2 ** 3 = 8

Example Code
a = 10
b=3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
print(a // b)
print(a ** b)

26
3.3. Relational (Comparison) Operators

Relational operators are used to compare values and return True or False.

List of Relational Operators


Operator Meaning Example

== Equal to 5 == 5 → True

!= Not equal 5 != 3 → True

> Greater than 10 > 5 → True

< Less than 3 < 5 → True

>= Greater than or equal 5 >= 5 → True

<= Less than or equal 3 <= 5 → True

Example Code
x = 10
y=5
print(x == y)
print(x != y)
print(x > y)
print(x < y)

27
3.4. Logical Operators
Logical operators are used to combine conditions.

Logical Operators
Operator Meaning

and True if both conditions are true

or True if at least one condition is true

not Reverses the result

Example Code
age = 20
marks = 80

print(age > 18 and marks >= 50)


print(age > 18 or marks < 50)
print(not age > 18)

Real-World Example: Login Check


username = "admin"
password = "1234"

print(username == "admin" and password == "1234")

28
3.5. Assignment Operators
Assignment operators are used to assign and update values.

Assignment Operators Table


Operator Example Meaning

= x=5 Assign

+= x += 3 x=x+3

-= x -= 2 x=x-2

*= x *= 2 x=x*2

/= x /= 2 x=x/2

Example Code
x = 10
x += 5
print(x)

x *= 2
print(x)

3.6. Membership Operators


Membership operators are used to check whether a value exists in a sequence (list, tuple,
string).

Membership Operators
Operator Meaning

29
in Exists in sequence

not in Does not exist

Example Code
languages = ["Python", "Java", "C++"]
print("Python" in languages)
print("PHP" not in languages)

3.7. Identity Operators


Identity operators compare memory location, not value.

Identity Operators
Operator Meaning

is Same object

is not Different object

Example Code
a = [1, 2, 3]
b=a
c = [1, 2, 3]

print(a is b)
print(a is c)
print(a == c)

📌 is checks identity, == checks value.

30
3.8. Operator Precedence
Operator precedence determines which operation executes first.

Example
result = 10 + 5 * 2
print(result)

📌 Multiplication runs before addition.

3.9. Common Beginner Mistakes

●​ Using = instead of ==
●​ Confusing is with ==
●​ Forgetting operator precedence

3.10. Summary
In this chapter, you learned:

●​ Arithmetic operators
●​ Relational operators

31
●​ Logical operators
●​ Assignment operators
●​ Membership and identity operators

Practice Exercises
1.​ Take two numbers and perform all arithmetic operations
2.​ Check if a user is eligible to vote using logical operators
3.​ Use membership operator on a list of courses
4.​ Compare two variables using is and ==

32
Chapter 4: Control Flow Statements in Python
Control flow statements allow a program to make decisions, repeat tasks, and control
execution flow. They are essential for writing real-world Python programs.

4.1. What are Control Flow Statements?


Control flow statements decide which code will run and how many times based on
conditions.

📌 Without control flow, programs would execute line by line with no decision-making.

4.2. Conditional Statements (if, elif, else)

Conditional statements are used to check conditions and execute code accordingly.

Basic if Statement
age = 20
if age >= 18:
print("You are eligible to vote")

33
if-else Statement
age = 16
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")

if-elif-else Statement
marks = 75

if marks >= 90:


print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")

34
4.3. Nested Conditions
Nested conditions mean using an if statement inside another if statement.

Example: Login System


username = "admin"
password = "1234"

if username == "admin":
if password == "1234":
print("Login successful")
else:
print("Wrong password")
else:
print("Invalid username")

35
4.4. Looping in Python
Loops are used to repeat a block of code multiple times.

Python supports:

●​ for loop
●​ while loop

4.5. for Loop

The for loop iterates over a sequence (list, range, string).

Example: Print Numbers


for i in range(1, 6):
print(i)

Example: Loop Through List


languages = ["Python", "Java", "C++"]
for lang in languages:
print(lang)

36
4.6. while Loop

The while loop runs as long as a condition is true.

Example
count = 1
while count <= 5:
print(count)
count += 1

4.7. Loop Control Statements

break Statement

Stops the loop immediately.

for i in range(1, 10):


if i == 5:
break
print(i)

37
continue Statement

Skips the current iteration and continues.

for i in range(1, 6):


if i == 3:
continue
print(i)

pass Statement

Does nothing and is used as a placeholder.

for i in range(5):
if i == 2:
pass
print(i)

38
4.8. Practical Examples

Example 1: Even or Odd Checker


num = int(input("Enter a number: "))

if num % 2 == 0:
print("Even number")
else:
print("Odd number")

Example 2: Multiplication Table


num = int(input("Enter a number: "))
for i in range(1, 11):
print(num, "x", i, "=", num * i)

Example 3: Password Retry System


correct_password = "python"

while True:
pwd = input("Enter password: ")

39
if pwd == correct_password:
print("Access granted")
break
else:
print("Try again")

4.9. Common Beginner Mistakes


●​ Infinite loops
●​ Missing indentation
●​ Incorrect condition logic

40
4.10. Summary
In this chapter, you learned:

●​ Conditional statements
●​ Nested conditions
●​ for and while loops
●​ break, continue, pass
●​ Practical real-world examples

Practice Exercises
1.​ Check whether a number is positive, negative, or zero
2.​ Print numbers from 1 to 100 using a loop
3.​ Create a login system with 3 attempts
4.​ Print all even numbers between 1 and 50

41
Part 3: Data Structures in Python

42
Chapter 5: Strings in Python
Strings are one of the most commonly used data types in Python. A string is a sequence of
characters used to store and manipulate text such as names, messages, passwords, emails,
and more.

5.1. What is a String?


A string is a collection of characters enclosed in quotes.

Python allows:

●​ Single quotes ' '


●​ Double quotes " "
●​ Triple quotes ''' ''' or """ """

String Creation Examples

name = 'Python'

language = "Programming"

message = """Welcome to Python Learning"""

5.2. Accessing Characters (Indexing)

Each character in a string has an index number, starting from 0.

Example

text = "Python"

print(text[0]) # P

print(text[3]) # h

43
Negative Indexing

print(text[-1]) # n

print(text[-2]) # o

5.3. String Slicing


Slicing is used to extract a part of a string.

Syntax

string[start : end]

Example

text = "Programming"

print(text[0:6])

print(text[3:8])

Slicing with Step

44
print(text[0:11:2])

5.4. String Length

Use len() to find string length.

name = "Python"

print(len(name))

5.5. Common String Methods


Python provides many built-in string methods.

Case Conversion

text = "python programming"

print([Link]())

print([Link]())

45
print([Link]())

Removing Spaces

msg = " Hello Python "

print([Link]())

print([Link]())

print([Link]())

Searching in Strings

text = "Learn Python"

print([Link]("Python"))

print([Link]("n"))

46
Replace Method

text = "I like Java"

print([Link]("Java", "Python"))

5.6. Checking String Content


text = "Python123"

print([Link]())

print([Link]())

print([Link]())

47
5.7. Formatting Strings
String formatting is used to insert variables into strings.

Method 1: f-Strings (Recommended)

name = "Ali"

age = 20

print(f"My name is {name} and I am {age} years old")

Method 2: format()

print("My name is {} and I am {} years old".format(name, age))

Method 3: % Operator (Old Style)

print("My name is %s and I am %d years old" % (name, age))

5.8. Real-World Examples

Example 1: Username Validation

username = input("Enter username: ")

if [Link]():

print("Valid username")

48
else:

print("Invalid username")

Example 2: Email Checker

email = input("Enter email: ")

if "@" in email and "." in email:

print("Valid email")

else:

print("Invalid email")

Example 3: Word Counter

sentence = input("Enter sentence: ")

print("Total words:", len([Link]()))

49
5.9. Common Beginner Mistakes
●​ Index out of range error
●​ Forgetting strings are immutable
●​ Confusing slicing indexes
●​ Index out of range error
●​ Forgetting strings are immutable
●​ Confusing slicing indexes

5.10. Summary
In this chapter, you learned:

●​ Creating strings
●​ Indexing and slicing
●​ String methods

50
●​ String formatting
●​ Real-world use cases

Practice Exercises
1.​ Reverse a string
2.​ Count vowels in a string
3.​ Check if a string is a palindrome
4.​ Format student result using f-string

51
Chapter 6: Lists in Python
Lists are one of the most powerful and flexible data structures in Python. A list can store
multiple values of different data types and is widely used in real-world Python programs.

6.1. What is a List?


A list is an ordered, mutable (changeable) collection of items enclosed in square brackets
[].

Example

numbers = [1, 2, 3, 4, 5]

names = ["Ali", "Sara", "Ahmed"]

mixed = [1, "Python", True, 10.5]

6.2. Creating Lists

Empty List

my_list = []

List Using Constructor

values = list((10, 20, 30))

List from User Input

items = input("Enter items separated by comma: ").split(",")

print(items)

52
6.3. List Indexing

Each element in a list has an index number, starting from 0.

Example

languages = ["Python", "Java", "C++"]

print(languages[0])

print(languages[2])

Negative Indexing

print(languages[-1])

53
6.4. List Slicing
Slicing is used to extract part of a list.

Syntax

list[start : end]

Example

numbers = [10, 20, 30, 40, 50]

print(numbers[1:4])

print(numbers[:3])

print(numbers[2:])

Slicing with Step

print(numbers[0:5:2])

54
6.5. Updating List Items
Lists are mutable, meaning their values can be changed.

numbers = [10, 20, 30]

numbers[1] = 99

print(numbers)

6.6. Common List Methods

Adding Elements

numbers = [1, 2, 3]

[Link](4)

[Link](1, 10)

Removing Elements

[Link](10)

[Link]()

[Link]()

Other Useful Methods

nums = [5, 2, 9, 1]

[Link]()

[Link]()

55
print(nums)

print(len(nums))

6.7. Looping Through a List


languages = ["Python", "Java", "C++"]

for lang in languages:

print(lang)

56
6.8. List Comprehensions
List comprehensions provide a short and clean way to create lists.

Basic Example

squares = [x*x for x in range(1, 6)]

print(squares)

With Condition

even_numbers = [x for x in range(1, 11) if x % 2 == 0]

print(even_numbers)

6.9. Nested Lists


A list inside another list is called a nested list.

Example

students = [

["Ali", 85],

["Sara", 90],

["Ahmed", 78]

57
print(students[0])

print(students[1][0])

Looping Through Nested List

for student in students:

print(student[0], student[1])

6.10. Real-World Examples

Example 1: Shopping Cart

cart = []

58
[Link]("Milk")

[Link]("Bread")

[Link]("Eggs")

print(cart)

Example 2: Student Marks Average

marks = [80, 75, 90, 85]

avg = sum(marks) / len(marks)

print("Average:", avg)

6.11. Common Beginner Mistakes


●​ IndexError (out of range)
●​ Confusing append() and insert()
●​ Modifying list while looping

59
6.12. Summary
In this chapter, you learned:

●​ Creating lists
●​ Indexing and slicing
●​ List methods
●​ List comprehensions
●​ Nested lists
●​ Real-world applications

Practice Exercises
1.​ Create a list of 5 numbers and find the maximum
2.​ Create a list of even numbers using list comprehension
3.​ Create a nested list of students and marks
4.​ Remove duplicate values from a list

60
Chapter 7: Tuples and Sets in Python
In this chapter, we will learn about Tuples and Sets, two important Python data structures. They
are used to store multiple values, but each has unique properties and use cases.

Part A: Tuples in Python

7.1. What is a Tuple?


A tuple is an ordered collection of items that is immutable, meaning its values cannot be
changed after creation.

Tuples are defined using parentheses ().

Example

numbers = (10, 20, 30)

names = ("Ali", "Sara", "Ahmed")

mixed = (1, "Python", True)

7.2. Tuple Immutability


Once a tuple is created, you cannot modify, add, or delete elements.

values = (10, 20, 30)

values[0] = 100 # Error

61
Why Use Tuples?

●​ Data safety (cannot be changed accidentally)


●​ Faster than lists
●​ Used for fixed data (coordinates, settings)

7.3. Creating Tuples

Single-Element Tuple

single = (10,)

Tuple Without Parentheses (Packing)

point = 5, 10

Tuple from List

my_list = [1, 2, 3]

my_tuple = tuple(my_list)

7.4. Tuple Indexing and Slicing


Tuples support indexing and slicing like lists.

colors = ("Red", "Green", "Blue", "Yellow")

print(colors[0])

62
print(colors[-1])

print(colors[1:3])

7.5. Tuple Operations

Length of Tuple

print(len(colors))

Concatenation

t1 = (1, 2)

t2 = (3, 4)

print(t1 + t2)

Repetition

print(t1 * 3)

7.6. Tuple Methods


Tuples have only two built-in methods.

nums = (10, 20, 10, 30)

print([Link](10))

print([Link](30))

63
7.7. Tuple Unpacking
student = ("Ali", 20, "A")

name, age, grade = student

print(name, age, grade)

Part B: Sets in Python

7.8. What is a Set?


A set is an unordered collection of unique elements. Duplicate values are not allowed.

Sets are defined using curly braces {}.

Example

numbers = {1, 2, 3, 4}

names = {"Ali", "Sara", "Ali"}

print(names)

64
7.9. Creating Sets

Empty Set (Important)

empty_set = set()

⚠️ {} creates an empty dictionary, not a set.


7.10. Set Properties
●​ Unordered
●​ Unique elements
●​ Mutable (can add/remove items)
●​ No indexing or slicing

7.11. Set Methods

Adding Elements

numbers = {1, 2, 3}

[Link](4)

Removing Elements

[Link](2)

[Link](10)

[Link]()

Clearing a Set

[Link]()

65
7.12. Set Operations

Union

a = {1, 2, 3}

b = {3, 4, 5}

print(a | b)

Intersection

print(a & b)

Difference

print(a - b)

Symmetric Difference

print(a ^ b)

66
7.13. Use Cases of Sets (Real-World Examples)

Example 1: Remove Duplicate Values

numbers = [1, 2, 2, 3, 4, 4]

unique_numbers = set(numbers)

print(unique_numbers)

Example 2: Common Students in Two Classes

class_a = {"Ali", "Sara", "Ahmed"}

class_b = {"Ahmed", "Zara", "Ali"}

print(class_a & class_b)

Example 3: Allowed Users Check

allowed_users = {"admin", "manager", "editor"}

user = input("Enter role: ")

if user in allowed_users:

print("Access granted")

67
else:

print("Access denied")

7.14. Tuple vs List vs Set (Quick Comparison)


Feature List Tuple Set

Ordered Yes Yes No

Mutable Yes No Yes

Duplicates Yes Yes No

Indexing Yes Yes No

7.15. Common Beginner Mistakes


●​ Forgetting comma in single-element tuple
●​ Trying to index a set
●​ Using {} instead of set()

68
7.16. Summary
In this chapter, you learned:

●​ What tuples are and why they are immutable


●​ Tuple operations and unpacking
●​ What sets are and their properties
●​ Set methods and operations
●​ Real-world use cases of sets

Practice Exercises
1.​ Create a tuple of 5 cities and unpack it
2.​ Convert a list with duplicates into a set
3.​ Find common elements between two sets
4.​ Check if a user is allowed using a set

69
Part 4: Functions and Modules

70
Part 5: File Handling and Error Management

71
Part 6: Object-Oriented Programming (OOP)

72
Part 7: Practical Python Applications

73
Part 8: Best Practices and Next Steps

74
Part 9: Appendices

75
Final Note
This book provides a strong foundation in Python programming and OOP, preparing
readers for real-world projects, frameworks, and advanced technologies.

Happy Learning 🚀
__Abid Maqsood

76

You might also like