Python
Python
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.
🔹 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
🔹 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
🧠 Explanation:
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
"""
🧪 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.
📝 Mini Quiz
✅ Answer in your mind or note them:
🔁 Recap
Concept Summary
Interpreted Executes line-by-line
Syntax Clean, uses indentation
Comments Use # or """ """
Case Sensitive a≠A
print() Used for console output
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.
🔹 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
❌ Not allowed:
userName = "Bob"
_user_age = 25
UserAge = 25 # different from userage
a, b, c = 1, 2, 3
x = y = z = "Python"
✅ String Formatting:
age = 21
print(f"My age is {age}") # f-string (best way)
✅ Concatenation:
a = "Hello"
b = "World"
print(a + " " + b)
x = 5
print(type(x)) # <class 'int'>
x = str(100) # '100'
y = int("50") # 50
z = float(10) # 10.0
🧠 Beware:
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:
🔁 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
Excellent! Let's dive into Module 3: Python Numbers, Arithmetic, and Booleans — explained
deeply with comparisons to C++, real-life examples, and practice questions.
Example:
x = 10 # int
y = 3.14 # float
z = 2 + 3j # 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
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 π
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
🧪 Practice Questions
🔸 Q1: Write a program that:
📝 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.
We’ll go step by step with explanations, comparisons to C++, examples, and exercises.
🔹 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)
🔹 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:
name = "Hassan"
age = 20
print(f"My name is {name} and I am {age} years old.")
🔹 9. Check Substrings
text = "Cybersecurity"
print("secure" in text) # True
print("hack" in text) # False
🧪 Practice Questions
🔸 Q1:
🔸 Q2:
🔸 Q3:
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?
We'll cover this deeply and clearly, with comparisons to C++, examples, and practice.
if condition:
# do this if condition is true
🟠 if-else Statement
age = 16
if age >= 18:
print("Eligible")
else:
print("Not eligible")
🔵 if-elif-else Ladder
marks = 75
🔹 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:
🔹 5. Nested if Statements
age = 20
student = True
🔹 6. pass Statement
If you want an empty if block:
if True:
pass # do nothing
🧪 Practice Questions
🔸 Q1:
Write a program to check if a number is even or odd.
🔸 Q2:
Under 13 → "Child"
13–19 → "Teenager"
20–59 → "Adult"
60 and above → "Senior"
🔸 Q3:
🔸 Q4:
🧠 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?
We’ll cover:
🔹 1. Why Loops?
Loops let you repeat code multiple times without writing it again.
✅ 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).
Output:
1 3 5 7 9
✅ Example:
i = 0
while i < 5:
print(i)
i += 1
Output: 0 1 2
Output: 0 1 2 4
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)
🧪 Practice Questions
🔸 Q1:
🔸 Q2:
🔸 Q3:
🔸 Q4:
🔸 Q5:
*
* *
* * *
🧠 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")
Perfect! Let’s move ahead to Module 7: Functions in Python — a critical step in writing clean,
reusable code.
🔹 1. What Is a Function?
A function is a block of code that runs only when it is called.
It helps you:
🔹 2. Defining a Function
✅ Basic Syntax:
def greet():
print("Hello, World!")
Hello, World!
greet("Hassan")
Parameters = placeholders
Arguments = actual values passed
result = add(5, 3)
print(result)
Output:
🔹 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
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
🧪 Practice Questions
🔸 P1:
🔸 P3:
Write a function that accepts any number of integers and returns their sum.
🔸 P4:
🧠 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?
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)
🔹 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()
🔹 9. List Comprehension
A short-hand for creating lists.
🧪 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:
🔸 P4:
Create a new list using list comprehension that stores squares of even numbers from 1 to 10.
🔸 P5:
🧠 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.
🔹 Syntax:
my_tuple = ("apple", "banana", "cherry")
⚠️Note:
Even though tuples look like lists, you cannot modify them (no append(), remove(),
etc.)
🧪 Tuple Examples
🔹 Create a Tuple
fruits = ("apple", "banana", "cherry")
print(fruits)
🔹 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
➕ 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
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:
🔷 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)
3️⃣Remove an Item
my_set.remove("banana") # Gives error if item not found
my_set.discard("banana") # No error if item not found
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"}
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:
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
3️⃣Comparison Operators
These operators compare values and return True or False:
4️⃣Logical Operators
These combine multiple conditions:
Example Understanding: