0% found this document useful (0 votes)
2 views37 pages

Python

This document serves as an introduction to Python programming for individuals with a C++ background, covering essential concepts such as Python's features, installation, syntax rules, variable handling, data types, arithmetic operations, and string manipulation. It emphasizes Python's ease of use, dynamic typing, and built-in functions while providing practical examples and exercises for reinforcement. The document is structured into modules, each focusing on different aspects of Python, with comparisons to C++ for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views37 pages

Python

This document serves as an introduction to Python programming for individuals with a C++ background, covering essential concepts such as Python's features, installation, syntax rules, variable handling, data types, arithmetic operations, and string manipulation. It emphasizes Python's ease of use, dynamic typing, and built-in functions while providing practical examples and exercises for reinforcement. The document is structured into modules, each focusing on different aspects of Python, with comparisons to C++ for better understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

Great!

Let’s start your Python journey with Module 1: Python Introduction, based on
W3Schools, but deeply explained for someone with a C++ background like you.

✅ Python Module 1: Introduction

🔹 1. What is Python?
Python is a powerful, high-level, interpreted programming language created by Guido van
Rossum in the late 1980s and released in 1991.

🧠 Key Features:

Feature Description
Interpreted Executes code line by line (no compiling needed)
Dynamically Typed No need to declare variable types
Easy-to read and write; closer to human language than machine
High-Level
language
Cross-platform Runs on Windows, Linux, macOS, etc.
Huge Standard Lib Includes modules for math, file I/O, web, JSON, regex, etc.
Web dev, scripting, AI/ML, data science, automation, hacking, game
Popular Use Cases
dev

🔹 2. Why Learn Python?


Benefit Why It Matters
Easy to Learn Short syntax, no semicolons or curly braces
Widely Used Google, YouTube, Instagram, NASA, Netflix all use Python
Community Support Massive number of libraries and tutorials
Great for Beginners Intuitive, error messages are readable
Versatile Can do web apps, scripts, games, ML, etc.

🔹 3. Installing Python
If you're on Windows:

1. Go to: https://www.python.org/downloads/
2. Download and install the latest version (check “Add Python to PATH” before installing).
3. Open Command Prompt or Terminal and type:
4. python --version

🔹 4. Python IDEs (Where to Write Code)


 IDLE: Comes with Python (beginner-friendly).
 VS Code: Powerful and customizable.
 PyCharm: Best for large Python projects.
 Jupyter Notebook: For data science, ML, etc.
 Online IDEs: Replit, W3Schools editor, etc.

🔹 5. First Python Program


📘 Code:
print("Hello, Python!")

🧠 Explanation:

 print() is a built-in function that outputs to the screen.


 "Hello, Python!" is a string.
 No semicolon ; is needed (unlike C++).
 No main() function is required.

🔹 6. Python Syntax Rules


✅ Indentation (VERY IMPORTANT):

Python uses indentation (spaces/tabs) to define blocks of code. Example:

if 5 > 2:
print("5 is greater than 2")

Don’t do this:

if 5 > 2:
print("Wrong!") # ❌ This will cause an error

✅ No Braces or Semicolons:
 Code blocks: use indentation, not {}.
 End of line: just press Enter, no ;.

🔹 7. Python Comments
# This is a single-line comment

"""
This is a
multi-line comment
"""

 Use # for single-line comments.


 Use triple quotes ''' or """ for docstrings or multi-line comments.

🔹 8. Python is Case Sensitive


a = 5
A = 10
print(a) # 5
print(A) # 10

 a and A are different variables.

🧪 Practice Exercises
🔸 Q1: Print this text using Python:
Welcome to Python!
Learning is fun.

🔸 Q2: Write a program to print your name, age, and college in 3 lines.

🔸 Q3: What’s the output of this code?


print("5" + "10")
print(5 + 10)

🔸 Q4: Fix the following Python code:


if 10 > 5:
print("10 is greater")

📝 Mini Quiz
✅ Answer in your mind or note them:

1. What keyword is used to print something?


2. What happens if you skip indentation in a block?
3. Is Python compiled or interpreted?
4. Do you need to use semicolons in Python?

🔁 Recap
Concept Summary
Interpreted Executes line-by-line
Syntax Clean, uses indentation
Comments Use # or """ """
Case Sensitive a≠A
print() Used for console output

✅ Next Module: Python Variables & Data Types


Would you like to move on to the next module now, or try the practice tasks first?

Awesome! Let's dive into Module 2: Python Variables & Data Types, the foundation of
everything you'll write in Python. This section on W3Schools is very beginner-friendly, but I’ll
explain it more deeply and show how it compares to C++ when relevant.

✅ Python Module 2: Variables, Data Types &


Type Casting

🔹 1. What is a Variable?
A variable stores data in memory so you can use it later. In Python, you don't declare a type—
just assign a value.

🧠 Python vs C++:

C++ Python
int x = 10; x = 10
string name = "John"; name = "John"
Data type must be declared Python infers the type

✅ Example:
x = 5
y = "Alice"
print(x)
print(y)

Output:

5
Alice

Python automatically knows x is an integer and y is a string.

🔹 2. Rules for Variable Names


✅ Allowed:

 Must start with a letter or _


 Can contain letters, numbers, underscores
 Case-sensitive (name ≠ Name)

❌ Not allowed:

 Can't start with a number (1x = 10 ❌)


 Can't use keywords like class, if, def, etc.

userName = "Bob"
_user_age = 25
UserAge = 25 # different from userage

🔹 3. Assigning Multiple Variables


Python allows multiple assignments in one line:

a, b, c = 1, 2, 3

Or assign one value to multiple variables:

x = y = z = "Python"

🔹 4. Variable Output Techniques


✅ Basic Print:
name = "Eve"
print("Name:", name)

✅ String Formatting:
age = 21
print(f"My age is {age}") # f-string (best way)

✅ Concatenation:
a = "Hello"
b = "World"
print(a + " " + b)

🧠 Note: + joins strings but adds numbers!

🔹 5. Data Types in Python


Python has the following built-in data types:

Type Example Description


int x = 10 Integer
float x = 3.14 Decimal number
str x = "Hello" String (text)
bool x = True Boolean: True or False
list x = [1, 2, 3] Ordered, changeable, allows duplicates
tuple x = (1, 2, 3) Ordered, unchangeable
set x = {1, 2, 3} Unordered, unique values only
dict x = {"name": "Sam"} Key-value pairs (map/hashmap)
🔹 6. Checking Data Type
Use the type() function:

x = 5
print(type(x)) # <class 'int'>

🔹 7. Type Casting (Converting Data Types)


You can manually convert between types using built-in functions:

x = str(100) # '100'
y = int("50") # 50
z = float(10) # 10.0

🧠 Beware:

int("abc") # ❌ error: invalid literal

🔹 8. Python is Dynamically Typed


Python variables can change type at any time:

x = 5 # x is int
x = "Five" # now x is str

This makes Python flexible, but also dangerous if you're not careful.

🧪 Practice Problems
🔸 Q1: Declare the following variables:

 Your name (string)


 Your age (int)
 Your height (float)
 Whether you're a student (boolean)

Then print all using f-strings.


🔸 Q2: Predict the output:
x = "10"
y = 5
print(x + str(y))

🔸 Q3: Fix the type error:


num = "50"
print(num + 10)

🔸 Q4: Assign a = b = c = "Cyber" and print them one by one.

📝 Quiz (Test Your Understanding)


1. What’s the output of type("42")?
2. Is Python statically or dynamically typed?
3. What happens if you try int("abc")?
4. Which is correct?
o 10 = x
o x = 10
5. What’s the difference between x = "5" and x = 5?

🔁 Summary
Concept Explanation
Variable Stores values; no need for explicit type
Multiple Assign Possible in one line
Data Types int, float, str, bool, list, tuple, etc.
type() Returns the data type of a variable
Type Casting Convert between data types manually
Dynamic Typing Variables can change type at runtime

🔜 Next Module: Python Numbers, Math Operations, and


Booleans
Would you like to continue immediately, or practice these exercises and let me know when to
continue?

Excellent! Let's dive into Module 3: Python Numbers, Arithmetic, and Booleans — explained
deeply with comparisons to C++, real-life examples, and practice questions.

✅ Python Module 3: Numbers, Arithmetic


Operations, and Booleans

🔹 1. Python Number Types


Python supports three main types of numbers:

Type Example Description


int 5, -10 Whole numbers
float 3.14, -7.0 Decimal numbers (floating point)
complex 3 + 5j Complex numbers (used in math/engineering)

🧠 You don’t need to define types — Python figures it out automatically.

Example:
x = 10 # int
y = 3.14 # float
z = 2 + 3j # complex

print(type(x)) # <class 'int'>


print(type(y)) # <class 'float'>
print(type(z)) # <class 'complex'>

🔹 2. Arithmetic Operators
Operator Symbol Description Example
Addition + Adds numbers 5 + 2 = 7
Subtract - Subtracts 5 - 2 = 3
Multiply * Multiplies 5 * 2 = 10
Divide / Divides (float result) 5 / 2 = 2.5
Floor // Division (no decimals) 5 // 2 = 2
Operator Symbol Description Example
Modulus % Remainder of division 5 % 2 = 1
Exponent ** Power 2 ** 3 = 8

📘 Example:
a = 15
b = 4

print(a + b) # 19
print(a - b) # 11
print(a * b) # 60
print(a / b) # 3.75
print(a // b) # 3
print(a % b) # 3
print(a ** b) # 50625

🔹 3. Built-in Math Functions


Python has powerful built-in math features:

import math

print(math.sqrt(16)) # 4.0
print(math.ceil(2.3)) # 3
print(math.floor(2.9)) # 2
print(math.pow(2, 3)) # 8.0
print(math.pi) # 3.141592653589793
Function Purpose
sqrt(x) Square root
ceil(x) Round up
floor(x) Round down
pow(x, y) x raised to the power y
pi Returns value of π

🔹 4. Type Casting in Math


Convert between number types easily:

x = 5 # int
y = float(x) # now y = 5.0
z = int(3.9) # z = 3 (truncates decimal)
🔹 5. Booleans (True / False)
Boolean values are used in conditions and logic operations.

is_raining = True
print(is_raining) # True
print(type(is_raining)) # <class 'bool'>

💡 Boolean in Expressions:
print(10 > 5) # True
print(5 == 3) # False
print(5 != 3) # True
Operator Meaning Example
== Equal to x == y
!= Not equal x != y
>< Greater/Less x > y
>= <= Greater/less or equal x >= y

🔹 6. Boolean as Integer
In Python:

True == 1 # ✅ True
False == 0 # ✅ True

So, you can add booleans like this:

print(True + True + False) # 2

🧪 Practice Questions
🔸 Q1: Write a program that:

 Stores your age


 Multiplies it by 2
 Prints the result

🔸 Q2: What’s the output of:


print(10 // 3)
print(10 % 3)

🔸 Q3: Use the math module to:

 Find the square root of 81


 Round up 7.1
 Round down 7.9

🔸 Q4: Write a boolean expression that checks if:


 x = 15
 y = 20
 Print whether x is less than y and y is less than 30

📝 Quick Quiz
1. What is the output of 5 ** 2?
2. What is math.floor(3.8)?
3. What data type is True?
4. What is 10 % 4?
5. Is False == 0 true or false?

🔁 Recap
Topic Summary
Numbers int, float, complex
Arithmetic Ops + - * / // % **
Booleans True/False, used in logic
Math Module math.sqrt(), math.ceil(), etc.
Type Conversion int(), float(), round(), etc.

Would you like to:

 ✅ Try the practice questions and quiz?


 🔜 Or move to Module 4: Strings and String Operations?
Excellent! Welcome to Module 4: Strings and String Operations — one of the most important
and frequently used concepts in Python and real-world programming.

We’ll go step by step with explanations, comparisons to C++, examples, and exercises.

🟩 Module 4: Python Strings and String


Operations

🔹 1. What Is a String?
A string in Python is a sequence of characters enclosed in quotes.

name = "Hassan"
greeting = 'Hello'

✅ You can use single (' ') or double (" ") quotes for strings.

In C++, you use double quotes " " for strings and single quotes 'a' for characters.
In Python, both ' ' and " " can be used for strings.

🔹 2. Multiline Strings
Use triple quotes ''' or """ for multi-line text:

msg = '''Hello,
This is Hassan.'''

🔹 3. String Indexing
You can access specific characters in a string by index number (starting from 0).

text = "Python"
print(text[0]) # P
print(text[1]) # y
print(text[-1]) # n (last character)
🔹 4. String Slicing
Use colon : to extract parts of a string:

word = "Cybersecurity"
print(word[0:6]) # Cyber (0 to 5)
print(word[6:]) # security (from 6 to end)
print(word[:6]) # Cyber (same as above)

Like C++ substrings, but easier and more readable.

🔹 5. String Length
Use len() to get string length:

text = "Hassan"
print(len(text)) # 6

🔹 6. String Methods
Here are some common built-in methods:

Method Description Example


.upper() Converts to uppercase "hi".upper() → "HI"
.lower() Converts to lowercase "HI".lower() → "hi"
.strip() Removes leading/trailing spaces " hello ".strip() → "hello"
.replace(a,b) Replace part of string "apple".replace("a","A") → "Apple"
.split() Splits into list by spaces (or other) "a b c".split() → ["a", "b", "c"]

🔹 7. String Concatenation (Joining Strings)


first = "Hello"
last = "Hassan"
print(first + " " + last) # Hello Hassan

Same as cout << in C++, but using + to join.

🔹 8. f-Strings (String Formatting)


The best way to combine variables and strings:

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

f-strings are faster and cleaner than "Hello " + name.

🔹 9. Check Substrings
text = "Cybersecurity"
print("secure" in text) # True
print("hack" in text) # False

🧪 Practice Questions
🔸 Q1:

Write a program that:

 Stores your name and college


 Prints: My name is ___ and I study at ___. using f-string

🔸 Q2:

Given text = " Hello Python ", print:

1. The length of text


2. The trimmed version (no spaces)
3. The first 5 characters

🔸 Q3:

Split the string "name,age,city" into a list using .split()


Then print each value on a separate line.
🔸 Q4:

If x = "CyberSecurity", what is:

1. x[0]
2. x[-1]
3. x[5:10]
4. "Secure" in x?

🧠 Quick Quiz
1. What does text.upper() do?
2. What is the output of len("Python")?
3. How do you remove white spaces from both ends of a string?
4. What is x[1:4] if x = "Hassan"?
5. How to insert variables into a string cleanly in Python?

Would you like to:

 🔁 Try the practice questions and quiz?


 Or move ahead to Module 5: Conditions and If Statements?

Awesome! Welcome to Module 5: Conditions and If Statements – a core part of programming


logic. You'll learn how Python makes decisions based on conditions — like checking if someone
is old enough to vote, or if a password is correct.

We'll cover this deeply and clearly, with comparisons to C++, examples, and practice.

🟩 Module 5: Conditions and If Statements in


Python

🔹 1. What is a Conditional Statement?


A conditional statement allows you to execute code only when a specific condition is true.
In Python, the structure looks like:

if condition:
# do this if condition is true

✅ Notice the colon : and indentation — indentation is required in Python!

🔹 2. if, elif, and else


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

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

🔵 if-elif-else Ladder
marks = 75

if marks >= 90:


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

Just like if-else if-else in C++!

🔹 3. Comparison Operators
Used to compare values:
Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or equal a >= b
<= Less or equal a <= b

🔹 4. Logical Operators
Used to combine conditions:

Operator Meaning Example


and Both must be true a > 10 and a < 20
or One must be true a == 5 or b == 10
not Reverses the result not(a == b) → True if false

🔹 5. Nested if Statements
age = 20
student = True

if age > 18:


if student:
print("Eligible as student over 18")

🔹 6. pass Statement
If you want an empty if block:

if True:
pass # do nothing

In C++ you'd leave {} empty — in Python, use pass.

🧪 Practice Questions
🔸 Q1:
Write a program to check if a number is even or odd.

🔸 Q2:

Check if a person is:

 Under 13 → "Child"
 13–19 → "Teenager"
 20–59 → "Adult"
 60 and above → "Senior"

🔸 Q3:

You’re given two numbers. Print the maximum using if.

🔸 Q4:

Check if a string is "admin" and password is "1234".


If both are correct, print: "Access Granted"
Else: "Access Denied"

🧠 Quick Quiz
1. What will this print?
2. a = 10
3. if a > 5 and a < 15:
4. print("Yes")
5. else:
6. print("No")
7. Which operator is used for "not equal"?
8. Write a condition to check if x is between 10 and 50 (inclusive).
9. What does elif stand for?
10. What is the purpose of the pass statement?

Would you like to:


 ✅ Solve the practice questions now?
 Or move ahead after the quiz?

Awesome! You're progressing smoothly.


Welcome to Module 6: Loops in Python — one of the most powerful tools in programming.

We’ll cover:

 for and while loops


 loop control (break, continue, else)
 real-world examples
 practice questions
...all explained clearly, deeply, and compared with C++ where needed.

🟩 Module 6: Loops in Python

🔹 1. Why Loops?
Loops let you repeat code multiple times without writing it again.

In C++, you use for, while, and do...while.


In Python, it's mainly for and while.

🔹 2. for Loop in Python


The for loop is often used to iterate over sequences like lists, strings, or a range of numbers.

✅ Basic Example:
for i in range(5):
print(i)

Output:

0
1
2
3
4
range(5) means: start at 0, go up to 4 (not including 5).

🔹 Loop with custom start & step


for i in range(1, 10, 2):
print(i)

Output:

1 3 5 7 9

🔹 Loop over a string


for letter in "Python":
print(letter)

🔹 3. while Loop in Python


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

✅ Example:
i = 0
while i < 5:
print(i)
i += 1

🔹 4. Loop Control Statements


✅ break – exit loop early
for i in range(5):
if i == 3:
break
print(i)

Output: 0 1 2

✅ continue – skip current iteration


for i in range(5):
if i == 3:
continue
print(i)

Output: 0 1 2 4

✅ else with loops


for i in range(3):
print(i)
else:
print("Loop finished")

This runs when the loop completes normally (not when broken).

🔹 5. Nested Loops
for i in range(2):
for j in range(3):
print(i, j)

Like C++ nested loops — one inside another.

🔹 6. Loop with pass


for i in range(3):
pass # used as placeholder

🔹 7. Difference between for and while


Feature for Loop while Loop
Use case Known number of repetitions Unknown repetitions
Structure Uses range() or iterable Uses condition
Exit control Automatically via range Manually with condition

🧪 Practice Questions
🔸 Q1:

Print numbers from 1 to 10 using a for loop.

🔸 Q2:

Print all even numbers from 1 to 20.

🔸 Q3:

Using while, print numbers from 10 to 1 (reverse order).

🔸 Q4:

Loop through the string "Cyber" and print each letter.

🔸 Q5:

Use a nested for loop to print:

*
* *
* * *

🧠 Quick Quiz
1. What will range(3, 10, 2) return?
2. What is the difference between break and continue?
3. What is the output of this code:

for i in range(3):
print(i)
else:
print("Done")

4. When would you prefer a while loop over a for loop?


5. How do you skip one loop cycle but keep the rest running?

Would you like to:

 ✅ Try the practice questions now?


 Or move ahead after doing the quiz?

Perfect! Let’s move ahead to Module 7: Functions in Python — a critical step in writing clean,
reusable code.

🟩 Module 7: Functions in Python

🔹 1. What Is a Function?
A function is a block of code that runs only when it is called.

It helps you:

 Organize your code


 Reuse logic
 Avoid repetition
 Debug easily

🔸 Similar to void or int functions in C/C++

🔹 2. Defining a Function
✅ Basic Syntax:
def greet():
print("Hello, World!")

✅ Calling the Function:


greet()
Output:

Hello, World!

🔹 3. Function with Parameters


✅ Example:
def greet(name):
print("Hello,", name)

greet("Hassan")

Parameters = placeholders
Arguments = actual values passed

🔹 4. Function with Return Value


def add(a, b):
return a + b

result = add(5, 3)
print(result)

Output:

return sends a value back to the caller.

🔹 5. Default Parameter Value


def greet(name="Guest"):
print("Hello,", name)

greet() # Uses default


greet("Ali") # Overrides default

🔹 6. Keyword Arguments
You can pass values using parameter names:
def student(name, age):
print(name, age)

student(age=20, name="Hassan")

🔹 7. Arbitrary Arguments
✅ *args: many positional arguments
def add_all(*nums):
total = 0
for n in nums:
total += n
return total

print(add_all(1, 2, 3, 4)) # 10

✅ **kwargs: many keyword arguments


def print_info(**info):
for key, value in info.items():
print(key, ":", value)

print_info(name="Hassan", age=20)

🔹 8. Recursion in Python
A function that calls itself.

def factorial(n):
if n == 1:
return 1
return n * factorial(n-1)

print(factorial(5)) # 120

Be careful! Recursion must have a base case to stop.

🧪 Practice Questions
🔸 P1:

Write a function that takes a name and prints "Hello, <name>".


🔸 P2:

Write a function that returns the square of a number.

🔸 P3:

Write a function that accepts any number of integers and returns their sum.

🔸 P4:

Write a recursive function to calculate the factorial of a number.

🧠 Quick Quiz
1. How do you define a function in Python?
2. What is the difference between *args and **kwargs?
3. What will this return?

def f(x=5):
return x * 2

print(f())
print(f(3))

4. What is recursion?
5. Can a function return multiple values in Python?

Ready to try the practice or quiz?

Great! Let’s move on to Module 8: Python Data Structures – Lists — one of the most
essential and powerful parts of Python programming.
🟩 Module 8: Python Lists
A list is a collection of items (elements) that is ordered, mutable (changeable), and allows
duplicates.

🔹 1. Creating a List
fruits = ["apple", "banana", "cherry"]
print(fruits)

 You can mix data types:

mixed = [1, "hello", 3.5, True]

🔹 2. Accessing List Items


print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)

🔹 3. Modifying List Items


fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry']

🔹 4. List Functions and Methods


Function/Method Description
len(list) Returns the number of items
list.append(x) Adds x to the end
list.insert(i, x) Inserts x at index i
list.remove(x) Removes first occurrence of x
list.pop(i) Removes item at index i (default last)
list.sort() Sorts the list in ascending order
list.reverse() Reverses the list
list.clear() Empties the list

🔹 5. Looping Through a List


for fruit in fruits:
print(fruit)

🔹 6. Checking for Existence


if "apple" in fruits:
print("Yes!")

🔹 7. List Slicing
nums = [1, 2, 3, 4, 5]
print(nums[1:4]) # [2, 3, 4]
print(nums[:3]) # [1, 2, 3]
print(nums[-2:]) # [4, 5]

🔹 8. Copying a List
new_list = fruits.copy()

⚠️new_list = fruits only creates a reference, not a true copy.

🔹 9. List Comprehension
A short-hand for creating lists.

squares = [x**2 for x in range(5)]


print(squares) # [0, 1, 4, 9, 16]

🧪 Practice Questions
🔸 P1:

Create a list of 5 numbers and print the sum of all numbers using a loop.

🔸 P2:

Add "grape" to the list fruits = ["apple", "banana"] and then remove "banana".
🔸 P3:

Sort a list of numbers in descending order.

🔸 P4:

Create a new list using list comprehension that stores squares of even numbers from 1 to 10.

🔸 P5:

Copy a list using both methods and explain the difference.

🧠 Quick Quiz
1. What are the characteristics of a list in Python?
2. How do you access the last element of a list?
3. What does list.append() do?
4. How can you sort a list in reverse (descending) order?
5. What is list comprehension?

Would you like to try the practice questions first, or jump to the quiz?

Great! Let's move on to 🔹 Module 9: Tuples — a key concept in Python when you want
immutable (unchangeable) sequences.

🔷 Module 9: Tuples in Python (Based on W3Schools)


✅ What is a Tuple?

 A tuple is a collection that is:


o Ordered
o Unchangeable (immutable)
o Allows duplicate values

🔹 Syntax:
my_tuple = ("apple", "banana", "cherry")

⚠️Note:

 Even though tuples look like lists, you cannot modify them (no append(), remove(),
etc.)

🔸 Why Use Tuples?


Feature Use When...
Immutable You want the data to be fixed
Faster Tuples are faster than lists in Python
Safe Prevents accidental modifications

🧪 Tuple Examples
🔹 Create a Tuple
fruits = ("apple", "banana", "cherry")
print(fruits)

🔹 Access Elements (Indexing)


print(fruits[1]) # Output: banana

🔹 Negative Indexing
print(fruits[-1]) # Output: cherry

🔹 Slicing Tuples
print(fruits[0:2]) # Output: ('apple', 'banana')
🔒 Tuple is Immutable
fruits = ("apple", "banana", "cherry")
fruits[1] = "orange" # ❌ Error: 'tuple' object does not support item
assignment

🔄 Loop Through Tuple


for fruit in fruits:
print(fruit)

➕ Combine Tuples
t1 = (1, 2)
t2 = (3, 4)
t3 = t1 + t2
print(t3) # Output: (1, 2, 3, 4)

📏 Tuple Length
print(len(fruits)) # Output: 3

⚠️Tuple with One Item


To create a one-item tuple, you must use a comma:

t = ("apple",)
print(type(t)) # Output: <class 'tuple'>

Without comma:

t = ("apple")
print(type(t)) # Output: <class 'str'>

🧪 Practice Questions
1. What will be the output of my_tuple = ("a", "b", "c") and print(my_tuple[2])?
2. Can you change a value inside a tuple? Why or why not?
3. How do you create a tuple with only one element?
4. Write code to combine two tuples.
5. Loop through a tuple of 4 numbers and print only even numbers.

Let me know when you're ready for the answers and practice codes, or to move to Module 10:
Sets!

Excellent! Let's move to the next important Python topic from W3Schools style learning:

✅ Module 10: Python Sets

🔷 What is a Set?
 A set is a collection that is:
o Unordered → No indexing
o Unchangeable elements → You can’t modify existing items, but you can
add/remove entire items
o No duplicates allowed
 Sets are useful for storing unique items.

🔧 Set Syntax
my_set = {"apple", "banana", "cherry"}
print(my_set)

 Order is not guaranteed in output


 Duplicates are removed automatically

🔹 Basic Set Operations


1️⃣Add an Item
my_set.add("orange")

2️⃣Add Multiple Items


my_set.update(["mango", "grapes"])

3️⃣Remove an Item
my_set.remove("banana") # Gives error if item not found
my_set.discard("banana") # No error if item not found

4️⃣Loop Through Set


for item in my_set:
print(item)

5️⃣Check Membership
if "apple" in my_set:
print("Apple is present")

🔹 Set Operations
Operation Example Description
Union set1.union(set2) Combine all unique items
Intersection set1.intersection(set2) Common items
Difference set1.difference(set2) Items in set1 but not in set2
Symmetric Difference set1.symmetric_difference(set2) Items in either set but not both

🧠 Example:
set1 = {"apple", "banana", "cherry"}
set2 = {"banana", "mango", "grapes"}

print(set1.union(set2)) # Combine both sets


print(set1.intersection(set2)) # Common item: banana
print(set1.difference(set2)) # Items in set1 but not set2

🔥 Quick Practice Questions


P1. Create a set of fruits and add "guava" to it.
P2. Remove "banana" using .discard() to avoid errors.
P3. Check if "apple" exists in the set.
P4. Find the union of two sets of numbers.
P5. Find the intersection of two sets of colors.

Would you like me to give code for practice questions or will you try them first?

Excellent! Let's move to the Next Module — Booleans & Operators, explained deeply, step by
step, with simple language and no confusion:

✅ Python Module: Booleans & Operators

1️⃣What is a Boolean?
 A Boolean represents only two possible values:
o True
o False
 Booleans are used for:
o Decision making (if conditions)
o Comparisons
o Logical checks

✅ Booleans come from real-world logic:

 Something is either True (correct)


 Or False (incorrect)

Example in real life:

 Is the light ON? → True


 Is the door open? → False

In Python, True and False always start with uppercase letters.

2️⃣Where Booleans are Used


 Checking if one number is bigger than another.
 Comparing two values (Are they equal? Are they different?).
 Inside if, elif, else for making decisions.

3️⃣Comparison Operators
These operators compare values and return True or False:

Operator Meaning Example


== Equal to 5 == 5 → True
!= Not equal to 3 != 4 → True
> Greater than 7 > 2 → True
< Less than 3 < 5 → True
>= Greater than or equal to 5 >= 5 → True
<= Less than or equal to 4 <= 6 → True

4️⃣Logical Operators
These combine multiple conditions:

Operator Meaning Example


and Both conditions must be True (5 > 2) and (3 < 4) → True
or At least one condition is True (5 > 2) or (3 > 4) → True
not Reverses the result (True ↔ False) not (5 > 2) → False

5️⃣Identity & Membership Operators


Type Operator Meaning
Identity is Checks if both are same object
Identity is not Checks if they are different
Membership in Checks if item is in a group
Membership not in Checks if item is not in a group

Example Understanding:

 "apple" in ["apple", "banana"] → True


 x is y → True only if both point to the same thing in memory.
🎯 Quick Real-Life Example
Condition Result
Are you older than 18? True/False
Is your name "Ali"? True/False
Are both conditions True? (and) True/False
Is at least one condition True? (or) True/False

🧠 Summary of Booleans & Operators


✅ Booleans only have two possible values: True or False.
✅ Used heavily in conditions and comparisons.
✅ Comparison operators: ==, !=, >, <, >=, <=.
✅ Logical operators combine conditions: and, or, not.
✅ Membership (in, not in) checks inside lists, etc.
✅ Identity (is, is not) checks if objects are same.

Would you like to:

1. Get practice questions on Booleans & Operators


2. Move to the next module: Control Flow (if, elif, else in detail)
3. See real examples with code

Tell me your choice!

You might also like