info.brilliantp@gmail.com
Brilliant P Logo

BRILLIANT P

Free Quality Education for Everyone | Turn Screen Time into Productive Time

Python Basics Masterclass Notes

Comprehensive step-by-step notes, real-life examples, quizzes & practice challenges.

Course Progress 0%
0 of 10 Modules Completed
Module 1 10 min read

Introduction to Python

1. Introduction in Simple Words

Imagine giving instructions to a friendly robot. If you speak in complex robot code, it's hard to learn. But if you talk in plain, simple English, it's easy! That is what Python is: a human-friendly programming language designed so anyone can give instructions to computers effortlessly.

Technical Definition: Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum in 1991. It emphasizes code readability with clear, elegant syntax.
2. Syntax & Features

Python code requires no complex boilerplate like C++ or Java. Writing text to the screen is as simple as calling print().

hello_world.py
# Example 1: Hello World in Python
print("Hello, Welcome to Brilliant P!")

# Example 2: Simple math calculation
# Python works like a super calculator
print(15 + 25)

# Example 3: Multiple print lines
print("Learning Python is fun!")
print("Let's turn screen time into productive time.")
Expected Output:
Hello, Welcome to Brilliant P! 40 Learning Python is fun! Let's turn screen time into productive time.

Real-Life Applications

  • Web Development: Sites like Instagram & YouTube use Python backends.
  • Artificial Intelligence: ChatGPT, Machine Learning, and Robotics.
  • Data Science & Analytics: Visualizing trends and processing statistics.
  • Automation Scripts: Automating repetitive daily computer tasks.

Common Beginner Mistakes

  • Case Sensitivity: print() works, but Print() causes an error.
  • Indentation Errors: Mixing spaces and tabs or random indentation.
  • Missing Quotes: Forgetting quotation marks around text strings.

Key Points to Remember

  • Python is an interpreted language—code runs line-by-line.
  • It is completely free, open-source, and beginner-friendly.
  • Code blocks are defined using indentation (spaces), not curly braces {}.

Practice Questions

1. Who created Python and in which year was it released?
Created by a Dutch programmer in 1991.
2. What function is used to display output on the screen in Python?
Starts with 'p' and ends with 'rint()'.
3. Is Python an interpreted or compiled language?
It executes code line-by-line without explicit pre-compilation.
4. Write a single line of Python code to print your name.
Use print("Your Name")
5. What symbol is used to write single-line comments in Python?
The hash symbol #.

Mini Challenge: Student Greeting Card

Write a Python script that displays a 3-line welcome banner for a new Brilliant P student, containing their platform tagline.
solution.py
print("=================================")
print("   WELCOME TO BRILLIANT P!       ")
print("Turn Screen Time into Productive Time!")
print("=================================")

Module 1 Quiz

5 Questions
1. Who created the Python programming language?
2. Which function outputs text to the screen?
3. How do you start a single-line comment in Python?
4. Python code is executed line-by-line by an...
5. What happens if you type PRINT("Hello") instead of print("Hello")?
Module 2 12 min read

Variables in Python

1. Introduction in Simple Words

Think of a variable as a labeled container or storage box in your kitchen. You put a sticker on the box that says sugar, and inside the box, you keep sugar. In Python, a variable is simply a named storage box in computer memory that holds data!

Technical Definition: A variable is a symbolic name associated with a memory location that stores a value. In Python, variables are created automatically when you assign a value to them using the assignment operator (=).
2. Syntax & Examples

Syntax: variable_name = value

variables_demo.py
# Example 1: Creating variables
student_name = "Gurpreet Singh"
age = 17
course_fee = 0.0  # Free course at Brilliant P

print(student_name)
print(age)

# Example 2: Multiple assignments in one line
x, y, z = 10, 20, 30
print(x, y, z)

# Example 3: Assigning same value to multiple variables
a = b = c = 100
print(a, b, c)

# Example 4: Updating variable value
score = 50
score = score + 10
print("Updated Score:", score)
Expected Output:
Gurpreet Singh 17 10 20 30 100 100 100 Updated Score: 60

Variable Naming Rules

  • Must start with a letter (a-z, A-Z) or an underscore (_).
  • Cannot start with a number (e.g. 2name is INVALID).
  • Can only contain alphanumeric characters & underscores (a-z, 0-9, _).
  • Case-sensitive (age, Age, and AGE are three distinct variables).
  • Cannot use reserved Python keywords (like if, for, class).

Common Mistakes

  • Using spaces: user name = "Ali" (Error! Use user_name).
  • Starting with number: 1st_place = "Gold" (SyntaxError).
  • Using reserved words: def = 5 (SyntaxError).

Key Points to Remember

  • Python has dynamic typing—you do NOT need to specify data type explicitly.
  • By convention, use snake_case for variable names in Python (e.g. student_score).
  • Constants are usually written in ALL_CAPS (e.g. MAX_LIMIT = 100).

Practice Questions

1. Which of the following is a valid variable name? (a) 1stNum (b) _my_var (c) my-var
Variables can start with an underscore but not numbers or hyphens.
2. How do you assign values 5, 10 to two variables x and y in a single line?
x, y = 5, 10
3. Are myVar and myvar the same variable in Python?
No, Python is strictly case-sensitive.
4. What is snake_case naming convention?
All lowercase words separated by underscores like student_first_name.
5. What happens if you try to print an unassigned variable?
Python raises a NameError.

Mini Challenge: Student Bio Card

Create variables for a student's name, age, city, and marks percentage, then print a formatted bio summary using those variables.
student_name = "Simranpreet Kaur"
age = 18
city = "Amritsar"
marks = 94.5

print("Student Name:", student_name)
print("Age:", age)
print("City:", city)
print("Marks Percentage:", marks, "%")

Module 2 Quiz

5 Questions
1. Which of the following is an INVALID variable name?
2. Which operator is used to assign a value to a variable?
3. Are variables "Age" and "age" identical in Python?
4. What is the result of a, b = 5, 10?
5. Which word cannot be used as a variable name?
Module 3 14 min read

Data Types in Python

1. Introduction in Simple Words

In real life, we deal with different kinds of information: whole numbers (like 5 apples), decimals (like 98.6°F temperature), text sentences (like "Hello!"), or True/False answers (like Is it raining?). In Python, these different kinds of information are called Data Types!

Technical Definition: A Data Type is an attribute of data which tells the Python compiler/interpreter how the programmer intends to use the data. Python provides fundamental built-in data types: int, float, str, and bool.
2. The Built-in Fundamental Data Types
data_types_demo.py
# 1. Integer (int) - Whole positive or negative numbers
students_count = 250

# 2. Float (float) - Numbers with decimal points
percentage = 95.8

# 3. String (str) - Sequence of characters enclosed in quotes
school_name = "Brilliant P Academy"

# 4. Boolean (bool) - True or False (Case-sensitive!)
is_course_free = True

# Using type() function to inspect data type
print(type(students_count))  # Output: <class 'int'>
print(type(percentage))      # Output: <class 'float'>
print(type(school_name))      # Output: <class 'str'>
print(type(is_course_free))  # Output: <class 'bool'>

# Type Conversion (Casting)
num_str = "50"
num_int = int(num_str)  # Converts String "50" to Integer 50
print(num_int + 10)    # Result: 60
Expected Output:
<class 'int'> <class 'float'> <class 'str'> <class 'bool'> 60

Type Conversion Functions

  • int() - Converts float or valid numerical string to integer.
  • float() - Converts integer or string to decimal float.
  • str() - Converts any value to string representation.
  • bool() - Converts value to True/False. (0, "", None become False).

Common Mistakes

  • Boolean Casing: Writing true instead of True causes NameError.
  • TypeError: Adding string and integer directly: "Age: " + 18 (Use str(18)).
  • Invalid int conversion: Trying int("hello") causes ValueError.

Key Points to Remember

  • Use type(variable) anytime you want to check the data type of a variable.
  • Strings can be enclosed in single quotes '...' or double quotes "...".
  • Booleans True and False must always start with capital letters.

Practice Questions

1. What is the data type of the value 3.14159?
Float (decimal number).
2. How do you convert the float 9.99 into an integer?
int(9.99) truncates to 9.
3. What is the output of type("100")?
Since 100 is inside quotes, it is a String (<class 'str'>).
4. What is the boolean value of integer 0?
bool(0) evaluates to False.
5. What happens when you execute print("10" + "20")?
String concatenation yields "1020".

Mini Challenge: Shopping Bill Calculator

Write a program that takes item price as a string "499.50", quantity as string "3", converts them to proper numerical types, calculates total bill, and prints the type of each variable.
price_str = "499.50"
qty_str = "3"

price = float(price_str)
quantity = int(qty_str)

total_bill = price * quantity

print("Total Amount Payable: ₹", total_bill)
print("Price Type:", type(price))
print("Quantity Type:", type(quantity))

Module 3 Quiz

5 Questions
1. Which function is used to check the data type of a variable?
2. What data type is 7.5?
3. Which of the following is a Boolean value in Python?
4. What is the output of int(7.8)?
5. How do you convert number 25 to string "25"?
Module 4 16 min read

Operators in Python

1. Introduction in Simple Words

Operators are special symbols that perform calculations or comparisons on values. If variables are your numbers, operators are your math actions like plus (+), minus (-), or checks like "is greater than" (>).

Technical Definition: An operator is a symbol that tells the Python interpreter to perform specific mathematical, relational, or logical manipulation. The values operated upon are called operands.
2. Major Categories of Operators
operators_demo.py
# 1. Arithmetic Operators (+, -, *, /, %, //, **)
a = 17
b = 5

print("Addition:", a + b)        # 22
print("Division:", a / b)        # 3.4 (Returns float)
print("Floor Division:", a // b)  # 3 (Removes decimal)
print("Modulus (Remainder):", a % b) # 2
print("Exponent (Power):", b ** 3) # 5^3 = 125

# 2. Comparison Operators (==, !=, >, <, >=, <=)
print("Is a equal to b?", a == b)    # False
print("Is a greater than b?", a > b) # True

# 3. Logical Operators (and, or, not)
has_passed = True
has_fee_paid = True

print("Eligible for Certificate?", has_passed and has_fee_paid) # True

# 4. Membership Operators (in, not in)
course_name = "Python Masterclass"
print("'Py' in course?", "Py" in course_name) # True
Expected Output:
Addition: 22 Division: 3.4 Floor Division: 3 Modulus (Remainder): 2 Exponent (Power): 125 Is a equal to b? False Is a greater than b? True Eligible for Certificate? True 'Py' in course? True

Operator Precedence (PEMDAS)

  • Parentheses () highest priority.
  • Exponentiation **
  • Multiplication *, Division /, Floor Div //, Modulus %
  • Addition +, Subtraction -
  • Comparison ==, >, <
  • Logical not, and, or (lowest).

Common Mistakes

  • Confusing = and ==: = assigns a value; == compares equality!
  • Division type: / ALWAYS yields float (e.g. 4 / 2 = 2.0).
  • Logic Error: Forgetting and requires BOTH conditions to be True.

Key Points to Remember

  • Use % (modulus) to check if a number is even or odd (num % 2 == 0).
  • Use // (floor division) when you want a whole number quotient.
  • Logical not flips True to False and False to True.

Practice Questions

1. What is the value of 10 % 3?
Remainder when 10 is divided by 3 (1).
2. What is the difference between 7 / 2 and 7 // 2?
7/2 is 3.5, while 7//2 is 3.
3. What is the output of 2 ** 4?
2 raised to power 4 = 16.
4. What will (True and False) or True evaluate to?
False or True = True.
5. What does the membership operator in do?
Checks if a sequence/character exists inside another.

Mini Challenge: Even / Odd Checker

Write a program using arithmetic and comparison operators that checks if a variable num = 47 is Even or Odd, and prints True if Even.
num = 47
is_even = (num % 2 == 0)
print("Is", num, "even?", is_even)

Module 4 Quiz

5 Questions
1. Which operator calculates division remainder?
2. Which operator calculates power / exponentiation?
3. What is the output of 5 == 5.0?
4. The expression True and False evaluates to:
5. What is 10 // 3?
Module 5 15 min read

Conditional Statements in Python

1. Introduction in Simple Words

Think about your daily decisions: "IF it is raining, I will carry an umbrella; ELSE IF it is sunny, I will wear sunglasses; ELSE I will wear a regular hat." Conditional statements allow computers to make smart decisions based on conditions!

Technical Definition: Conditional Statements execute specific blocks of code depending on whether a given boolean condition evaluates to True or False. Python uses if, elif, and else.
2. Syntax & Examples
conditionals_demo.py
# Example 1: Simple if-else statement
age = 18

if age >= 18:
    print("You are eligible to vote!")
else:
    print("You are not eligible yet.")

# Example 2: Grade Evaluation using if-elif-else
marks = 85

if marks >= 90:
    grade = "A+"
elif marks >= 80:
    grade = "A"
elif marks >= 70:
    grade = "B"
else:
    grade = "C"

print("Your Grade is:", grade)

# Example 3: Short-hand Ternary Operator
status = "Adult" if age >= 18 else "Minor"
print("Status:", status)
Expected Output:
You are eligible to vote! Your Grade is: A Status: Adult

Flow Control Rules

  • if condition starts decision tree.
  • elif (short for else if) tests subsequent conditions if previous ones failed.
  • else catches everything when no previous condition was met.
  • Indentation (4 spaces) defines which code belongs inside the condition block.

Common Mistakes

  • Missing Colon :: Writing if x > 5 without a colon at the end.
  • Indentation Error: Forgetting to indent code inside the if block.
  • Using = instead of ==: Writing if x = 10: causes a SyntaxError.

Key Points to Remember

  • Python uses elif instead of else if.
  • Nested if statements mean an if block placed inside another if block.
  • Only ONE branch in an if-elif-else chain executes.

Practice Questions

1. What keyword is used to test secondary conditions in Python?
elif
2. What punctuation character must end every if, elif, and else line?
A colon :
3. What will be printed if x = 10 and code is if x > 15: print("A") else: print("B")?
B (since 10 > 15 is False).
4. Is the else block mandatory in every if statement?
No, if statements can exist independently without else.
5. What is a ternary conditional expression?
A one-line shorthand if-else statement.

Mini Challenge: Admission Eligibility System

Write a program that checks student score and fee status: IF score >= 80 AND fee_paid is True, print "Admission Approved", ELSE IF score >= 80 BUT fee_paid is False, print "Pending Fee Payment", ELSE print "Not Eligible".
score = 85
fee_paid = False

if score >= 80 and fee_paid:
    print("Admission Approved!")
elif score >= 80 and not fee_paid:
    print("Pending Fee Payment")
else:
    print("Not Eligible")

Module 5 Quiz

5 Questions
1. Which keyword means "else if" in Python?
2. What symbol is required at the end of an if statement line?
3. How does Python know which code belongs inside an if block?
4. What is the output of print("Yes") if 15 > 20 else print("No")?
5. Can you write an if statement without an else block?
Module 6 18 min read

Loops in Python

1. Introduction in Simple Words

Imagine your teacher asks you to write "I will learn Python" 100 times on a blackboard. Writing it manually takes hours. But with a computer loop, you write the line ONCE and tell Python: "Repeat this 100 times!" That is what loops do—repeat tasks automatically!

Technical Definition: A Loop is a control structure used to execute a block of code repeatedly as long as a specified condition remains true or for each item in a sequence. Python supports for loops and while loops.
2. Python Loop Types & Statements
loops_demo.py
# 1. for loop with range(start, stop, step)
print("Counting 1 to 5:")
for i in range(1, 6):
    print("Number:", i)

# 2. while loop - repeats while condition is True
count = 3
while count > 0:
    print("Countdown:", count)
    count -= 1

# 3. break statement - exits loop immediately
for num in range(1, 10):
    if num == 4:
        break
    print("Loop item:", num)

# 4. continue statement - skips current iteration
for x in range(1, 5):
    if x == 3:
        continue  # Skips 3
    print("Value:", x)
Expected Output:
Counting 1 to 5: Number: 1 Number: 2 Number: 3 Number: 4 Number: 5 Countdown: 3 Countdown: 2 Countdown: 1 Loop item: 1 Loop item: 2 Loop item: 3 Value: 1 Value: 2 Value: 4

Loop Keywords Explained

  • range(stop) - Generates numbers 0 up to (stop-1).
  • break - Terminates the loop immediately.
  • continue - Skips remaining code in current step and goes to next step.
  • pass - Placeholder statement that does nothing (prevents syntax errors).

Common Mistakes

  • Infinite Loops: Forgetting to update counter in while loop (e.g. count -= 1).
  • Off-by-one error: range(1, 5) stops at 4, NOT 5!
  • Incorrect Indentation: Putting statements outside the loop accidentally.

Key Points to Remember

  • Use for loops when you know how many times to repeat.
  • Use while loops when repeating based on a dynamic condition.
  • range(1, 10, 2) generates odd numbers: 1, 3, 5, 7, 9 (step = 2).

Practice Questions

1. What numbers are generated by range(3)?
0, 1, 2 (stops before 3).
2. Which keyword stops a loop completely?
break
3. How do you skip printing number 5 in a loop?
Use if i == 5: continue
4. What causes a while loop to run forever?
When the condition remains permanently True without updating.
5. What does the pass statement do?
It acts as a null placeholder statement doing nothing.

Mini Challenge: Multiplication Table Generator

Write a for loop to print the multiplication table of 7 from 7 x 1 = 7 up to 7 x 10 = 70.
num = 7
for i in range(1, 11):
    print(num, "x", i, "=", num * i)

Module 6 Quiz

5 Questions
1. What values does range(1, 5) produce?
2. Which statement terminates a loop immediately?
3. What does continue do inside a loop?
4. A while loop continues executing as long as its condition is:
5. Which keyword is a null placeholder statement in Python?
Module 7 18 min read

Functions in Python

1. Introduction in Simple Words

Think of a function like a juice blender or a recipe. You press a button (call the function), give it ingredients (parameters), and it performs the mixing and gives you delicious fresh juice (returns a result). Once created, you can use the blender as many times as you want without building a new machine!

Technical Definition: A Function is a reusable block of organized code designed to perform a specific task. Functions take inputs (parameters), process them, and optional return output using the return statement. Defined using the def keyword.
2. Function Definition & Calls
functions_demo.py
# 1. Defining a function with parameters
def greet_student(name, course="Python"):
    """This function greets a student."""
    return f"Hello {name}, welcome to {course} at Brilliant P!"

# Calling the function
message1 = greet_student("Amritpal")
message2 = greet_student("Gurnain", "Web Dev")

print(message1)
print(message2)

# 2. Function returning calculated result
def calculate_total(price, tax_rate):
    total = price + (price * tax_rate)
    return total

bill = calculate_total(500, 0.18)
print("Total Bill:", bill)

# 3. Anonymous Lambda Function (One-line function)
square = lambda x: x * x
print("Square of 6:", square(6))
Expected Output:
Hello Amritpal, welcome to Python at Brilliant P! Hello Gurnain, welcome to Web Dev at Brilliant P! Total Bill: 590.0 Square of 6: 36

Why Use Functions?

  • Reusability (DRY Principle): Don't Repeat Yourself. Write once, use everywhere.
  • Modularity: Breaks large programs into smaller, manageable chunks.
  • Easier Debugging: Isolate bugs quickly inside individual functions.

Common Mistakes

  • Forgetting to call: Defining a function with def doesn't run it until you call my_func().
  • Local vs Global Scope: Variables created inside a function cannot be accessed outside it.
  • Missing return: If a function lacks return, it implicitly returns None.

Key Points to Remember

  • Use def function_name(parameters): to define a function.
  • Default parameters (e.g. course="Python") allow optional arguments.
  • Keywords arguments allow passing parameters in any order (e.g. func(b=2, a=1)).

Practice Questions

1. What keyword is used to define a function in Python?
def
2. What does a function return if no return statement is written?
None
3. What is the difference between parameters and arguments?
Parameters are variables in function definition; arguments are actual values passed when calling.
4. What is a lambda function in Python?
A small single-line anonymous function defined with lambda keyword.
5. What is local variable scope?
Variables declared inside a function are accessible only within that function.

Mini Challenge: Student Marks Average Calculator

Write a function calculate_avg(m1, m2, m3) that receives marks for 3 subjects, returns the average score, and prints "Passed" if avg >= 50.
def calculate_avg(m1, m2, m3):
    avg = (m1 + m2 + m3) / 3
    if avg >= 50:
        status = "Passed"
    else:
        status = "Failed"
    return avg, status

average, result = calculate_avg(85, 90, 78)
print(f"Average Score: {average:.2f} | Result: {result}")

Module 7 Quiz

5 Questions
1. Which keyword defines a function in Python?
2. Which statement sends a result back from a function?
3. What is returned if a function does NOT have a return statement?
4. Arguments passed using parameter names (e.g. age=18) are called:
5. Which keyword creates an inline anonymous function?
Module 8 20 min read

Lists in Python

1. Introduction in Simple Words

Imagine a digital shopping list or a pouch with multiple pockets. Instead of creating 10 different variables for 10 students, you store all student names inside a single ordered collection called a List!

Technical Definition: A List is a built-in Python data structure that stores an ordered, mutable (changeable) collection of items enclosed in square brackets [...]. Lists support duplicate elements and items of mixed data types.
2. Creating, Indexing, Slicing & Modifying Lists
lists_demo.py
# 1. Creating a list
courses = ["Python", "Calligraphy", "Canva", "Web Dev"]

# 2. Accessing elements using zero-based indexing
print("First course:", courses[0])   # Python
print("Last course:", courses[-1])   # Web Dev (Negative index)

# 3. List Slicing [start : stop]
print("First 2 courses:", courses[0:2])

# 4. Adding elements: append(), insert()
courses.append("Video Editing")       # Adds to end
courses.insert(1, "Data Science")    # Inserts at index 1
print("After additions:", courses)

# 5. Removing elements: remove(), pop()
courses.remove("Canva")
popped_item = courses.pop(0)  # Removes item at index 0

# 6. Sorting & Reversing
numbers = [45, 12, 89, 3, 27]
numbers.sort()
print("Sorted numbers:", numbers)

# 7. List Comprehension (Fast list creation)
squares = [x**2 for x in range(1, 6)]
print("Squares list:", squares)
Expected Output:
First course: Python Last course: Web Dev First 2 courses: ['Python', 'Calligraphy'] After additions: ['Python', 'Data Science', 'Calligraphy', 'Canva', 'Web Dev', 'Video Editing'] Sorted numbers: [3, 12, 27, 45, 89] Squares list: [1, 4, 9, 16, 25]

Useful List Methods

  • append(item) - Adds item to the end.
  • insert(index, item) - Inserts item at specific index.
  • remove(item) - Removes first occurrence of item.
  • pop(index) - Removes & returns item at index.
  • len(list) - Returns total number of items in list.

Common Mistakes

  • IndexError: Trying my_list[5] on a list with only 3 items.
  • Remembering 0-index: First item is index 0, NOT 1!
  • sort() mutates list in-place: Writing sorted_list = my_list.sort() sets variable to None!

Key Points to Remember

  • Lists use square brackets [...].
  • Lists are mutable (elements can be modified, replaced, or deleted).
  • Negative indices start from end: -1 is last item, -2 is second last.

Practice Questions

1. How do you access the last element of a list named items?
items[-1]
2. What method adds a single element to the end of a list?
append()
3. What does len([10, 20, 30]) return?
3 (total number of elements).
4. What is the difference between remove() and pop()?
remove() deletes by value; pop() deletes by index position.
5. What is list comprehension?
A concise syntax to construct new lists from existing iterables.

Mini Challenge: Student Marks Analyzer

Given a list of student marks [78, 92, 45, 88, 60], write code to find the highest mark, lowest mark, and total average mark.
marks = [78, 92, 45, 88, 60]

highest = max(marks)
lowest = min(marks)
avg = sum(marks) / len(marks)

print("Highest Marks:", highest)
print("Lowest Marks:", lowest)
print(f"Average Marks: {avg:.2f}")

Module 8 Quiz

5 Questions
1. Which brackets are used to create a List in Python?
2. Which method adds an item to the end of a list?
3. How do you access the last item of a list my_list?
4. What does lst.pop(1) do?
5. Are Python lists mutable (modifiable)?
Module 9 12 min read

Tuples in Python

1. Introduction in Simple Words

Imagine a passport or birth certificate. Once issued, the details cannot be erased or modified. In Python, a Tuple is an unchangeable (immutable) list of values. When you want to ensure data remains safe from accidental modification, use a tuple!

Technical Definition: A Tuple is an ordered, immutable collection of elements enclosed in parentheses (...). Once created, items cannot be added, removed, or changed.
2. Creating, Accessing & Unpacking Tuples
tuples_demo.py
# 1. Creating a Tuple
dimensions = (1920, 1080)
colors = ("Red", "Green", "Blue")

# 2. Accessing elements via indexing
print("Screen Width:", dimensions[0])
print("Primary Color:", colors[0])

# 3. Tuple Unpacking
r, g, b = colors
print(f"Red channel: {r}, Green channel: {g}")

# 4. Tuple Methods: count() and index()
sample = (1, 2, 2, 3, 4, 2)
print("Count of 2:", sample.count(2))  # 3
print("Index of 4:", sample.index(4))  # 4

# Single item tuple MUST have a trailing comma!
single_tuple = ("Python",)  # Notice comma
print(type(single_tuple))  # <class 'tuple'>
Expected Output:
Screen Width: 1920 Primary Color: Red Red channel: Red, Green channel: Green Count of 2: 3 Index of 4: 4 <class 'tuple'>

List vs Tuple Comparison

  • Lists []: Mutable (changeable), slower performance, used for dynamic data.
  • Tuples (): Immutable (read-only), faster performance, memory efficient.
  • Use tuples for fixed data like GPS coordinates (lat, long), RGB values, or database IDs.

Common Mistakes

  • TypeError on mutation: Writing tup[0] = 5 causes TypeError: 'tuple' object does not support item assignment.
  • Single element without comma: Writing (5) is integer 5, NOT a tuple! Use (5,).

Key Points to Remember

  • Tuples are defined using round parentheses (...).
  • They are immutable—ideal for protecting data integrity.
  • Tuples can be used as dictionary keys because they are hashable.

Practice Questions

1. Which brackets are used to create a Tuple in Python?
Parentheses ()
2. Can you modify or append elements to a tuple after creation?
No, tuples are immutable.
3. How do you declare a tuple with a single element "hello"?
("hello",) with a trailing comma.
4. What is tuple unpacking?
Assigning tuple items directly into individual variables like x, y = (10, 20).
5. What are the two built-in tuple methods?
count() and index()

Mini Challenge: GPS Coordinate Printer

Create a tuple storing latitude and longitude coordinates (31.6340, 74.8723) for Amritsar, unpack them into lat and lon, and display formatted location data.
amritsar_coords = (31.6340, 74.8723)

lat, lon = amritsar_coords

print(f"City: Amritsar | Latitude: {lat}° N | Longitude: {lon}° E")

Module 9 Quiz

5 Questions
1. Which brackets define a tuple?
2. What happens if you try to execute tup[0] = 99?
3. Which of the following is a valid single-element tuple?
4. What is a, b = (10, 20) called?
5. Which method counts occurrences of an item in a tuple?
Module 10 22 min read

Dictionaries in Python

1. Introduction in Simple Words

Think of a real English dictionary or phone contact book. You look up a word like "Python" (the key) and find its meaning "A programming language" (the value). In Python, a Dictionary stores data as Key: Value pairs!

Technical Definition: A Dictionary is an ordered (as of Python 3.7+), mutable collection of key-value pairs enclosed in curly braces {key: value}. Keys must be unique and immutable data types (like strings or numbers).
2. Creating, Accessing & Updating Dictionaries
dictionaries_demo.py
# 1. Creating a Dictionary
student = {
    "name": "Harneet Kaur",
    "roll_no": 101,
    "courses": ["Python", "Calligraphy"],
    "is_enrolled": True
}

# 2. Accessing values using keys
print("Student Name:", student["name"])
print("Safe access with .get():", student.get("city", "Not Provided"))

# 3. Adding and Updating key-value pairs
student["city"] = "Ludhiana"  # Adds new key
student["roll_no"] = 105       # Updates existing key

# 4. Dictionary Methods: keys(), values(), items()
print("Keys:", list(student.keys()))
print("Values:", list(student.values()))

# 5. Iterating through dictionary
for key, value in student.items():
    print(f"{key} -> {value}")
Expected Output:
Student Name: Harneet Kaur Safe access with .get(): Not Provided Keys: ['name', 'roll_no', 'courses', 'is_enrolled', 'city'] Values: ['Harneet Kaur', 105, ['Python', 'Calligraphy'], True, 'Ludhiana'] name -> Harneet Kaur roll_no -> 105 courses -> ['Python', 'Calligraphy'] is_enrolled -> True city -> Ludhiana

Dictionary Methods

  • get(key, default) - Returns value safely without raising KeyError if missing.
  • keys() - Returns all keys in dictionary.
  • values() - Returns all values.
  • items() - Returns list of (key, value) tuples.
  • pop(key) - Removes specified key and returns its value.

Common Mistakes

  • KeyError: Trying dict["missing_key"] (Use .get() instead!).
  • Duplicate Keys: Keys must be unique! Duplicate keys overwrite previous values.
  • Mutable Keys: Lists cannot be used as dictionary keys (tuples can).

Key Points to Remember

  • Dictionaries are defined using curly braces {key: value}.
  • They offer ultra-fast $O(1)$ lookup times using key hashing.
  • Nested dictionaries mean storing dictionaries inside dictionaries (e.g. JSON data).

Practice Questions

1. How do you create an empty dictionary in Python?
{} or dict()
2. What method safely retrieves a value without crashing if key is missing?
.get(key)
3. Can a Python dictionary have duplicate keys?
No, keys must be unique. The last value assigned will overwrite earlier ones.
4. Which method returns both key and value pairs during loops?
.items()
5. What data types are allowed as dictionary keys?
Immutable types like strings, integers, floats, and tuples.

Mini Challenge: Student Grade Portal

Create a dictionary storing marks for 3 subjects {"Python": 92, "WebDev": 88, "Canva": 95}, calculate total marks and print each subject score line-by-line.
student_marks = {
    "Python": 92,
    "WebDev": 88,
    "Canva": 95
}

total = sum(student_marks.values())

for subject, mark in student_marks.items():
    print(f"Subject: {subject} -> Marks: {mark}")

print("Total Marks Obtained:", total)

Module 10 Quiz

5 Questions
1. How does a Dictionary store data?
2. Which brackets are used to create a Dictionary?
3. What is the safest way to access a key without raising a KeyError?
4. Can a dictionary contain duplicate keys?
5. Which method returns both key and value pairs for looping?

Python Terms Glossary

Quick reference guide for essential programming terminology.

Variable
A named memory storage box used to hold data values.
Data Type
Classification specifying what type of value a variable holds (int, float, str, bool).
Indentation
Leading spaces defining code block hierarchy in Python instead of curly braces.
Interpreter
Program that executes Python code line-by-line directly without pre-compilation.
Immutability
Property of objects (like tuples & strings) whose values cannot be modified after creation.
List Comprehension
Concise syntax for creating lists based on existing iterables in a single line.
Lambda Function
Small anonymous single-line function defined using the lambda keyword.
Modulus Operator (%)
Arithmetic operator returning the remainder of division between two numbers.

Final Beginner Python Assessment

Test your complete understanding of all 10 Python modules!

1. Who created Python in 1991?
2. Which of the following is an INVALID variable name?
3. What is the output of type(3.14)?
4. Which operator performs integer floor division?
5. Which keyword is short for "else if" in Python?
6. What sequence does range(5) generate?
7. Which keyword is used to define functions in Python?
8. Which list method adds an item to the end of a list?
9. Tuples are enclosed in () and are:
10. Dictionaries store data as: