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.
Python code requires no complex boilerplate like C++ or Java. Writing text to the screen is as simple as calling print().
# 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.")
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, butPrint()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
Mini Challenge: Student Greeting Card
print("=================================")
print(" WELCOME TO BRILLIANT P! ")
print("Turn Screen Time into Productive Time!")
print("=================================")
Module 1 Quiz
5 QuestionsVariables 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!
=).
Syntax: variable_name = value
# 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)
Variable Naming Rules
- Must start with a letter (a-z, A-Z) or an underscore (
_). - Cannot start with a number (e.g.
2nameis INVALID). - Can only contain alphanumeric characters & underscores (a-z, 0-9, _).
- Case-sensitive (
age,Age, andAGEare three distinct variables). - Cannot use reserved Python keywords (like
if,for,class).
Common Mistakes
- Using spaces:
user name = "Ali"(Error! Useuser_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_casefor variable names in Python (e.g.student_score). - Constants are usually written in ALL_CAPS (e.g.
MAX_LIMIT = 100).
Practice Questions
myVar and myvar the same variable in Python?Mini Challenge: Student Bio Card
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 QuestionsData 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!
int, float, str, and bool.
# 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
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
trueinstead ofTruecauses NameError. - TypeError: Adding string and integer directly:
"Age: " + 18(Usestr(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
TrueandFalsemust always start with capital letters.
Practice Questions
3.14159?9.99 into an integer?type("100")?0?print("10" + "20")?Mini Challenge: Shopping Bill Calculator
"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 QuestionsOperators 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" (>).
# 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
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
andrequires 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
notflips True to False and False to True.
Practice Questions
10 % 3?7 / 2 and 7 // 2?2 ** 4?(True and False) or True evaluate to?in do?Mini Challenge: Even / Odd Checker
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 QuestionsConditional 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!
True or False. Python uses if, elif, and else.
# 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)
Flow Control Rules
ifcondition starts decision tree.elif(short for else if) tests subsequent conditions if previous ones failed.elsecatches everything when no previous condition was met.- Indentation (4 spaces) defines which code belongs inside the condition block.
Common Mistakes
- Missing Colon
:: Writingif x > 5without a colon at the end. - Indentation Error: Forgetting to indent code inside the
ifblock. - Using
=instead of==: Writingif x = 10:causes a SyntaxError.
Key Points to Remember
- Python uses
elifinstead ofelse if. - Nested
ifstatements mean anifblock placed inside anotherifblock. - Only ONE branch in an
if-elif-elsechain executes.
Practice Questions
if, elif, and else line?x = 10 and code is if x > 15: print("A") else: print("B")?else block mandatory in every if statement?Mini Challenge: Admission Eligibility System
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 QuestionsLoops 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!
for loops and while loops.
# 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)
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
whileloop (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
forloops when you know how many times to repeat. - Use
whileloops when repeating based on a dynamic condition. range(1, 10, 2)generates odd numbers: 1, 3, 5, 7, 9 (step = 2).
Practice Questions
range(3)?pass statement do?Mini Challenge: Multiplication Table Generator
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 QuestionsFunctions 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!
return statement. Defined using the def keyword.
# 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))
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
defdoesn't run it until you callmy_func(). - Local vs Global Scope: Variables created inside a function cannot be accessed outside it.
- Missing return: If a function lacks
return, it implicitly returnsNone.
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
return statement is written?Mini Challenge: Student Marks Average Calculator
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 QuestionsLists 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!
[...]. Lists support duplicate elements and items of mixed data types.
# 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)
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, NOT1! sort()mutates list in-place: Writingsorted_list = my_list.sort()sets variable toNone!
Key Points to Remember
- Lists use square brackets
[...]. - Lists are mutable (elements can be modified, replaced, or deleted).
- Negative indices start from end:
-1is last item,-2is second last.
Practice Questions
items?len([10, 20, 30]) return?remove() and pop()?Mini Challenge: Student Marks Analyzer
[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 QuestionsTuples 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!
(...). Once created, items cannot be added, removed, or changed.
# 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'>
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] = 5causesTypeError: 'tuple' object does not support item assignment. - Single element without comma: Writing
(5)is integer5, 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
Mini Challenge: GPS Coordinate Printer
(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 QuestionsDictionaries 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!
{key: value}. Keys must be unique and immutable data types (like strings or numbers).
# 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}")
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
Mini Challenge: Student Grade Portal
{"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)