BRAINBIT INFOTECH PVT LTD · RANCHI
COMPLETE PYTHON COURSE · PART 1 OF 5

Python Foundations

Write your first programs: print, variables, input, operators, strings, decisions and loops.

6 modules~17.5 hours30 practice examplesNo coding needed

By the end of this part you can build

  • A GST bill, a tea-stall bill and an EMI calculator
  • A grade calculator and a login check
  • A number guessing game and an ATM PIN check
  • Neat invoices and timetables with f-strings

Every code example has a ▶ Run button. Click ✎ Edit & Run, or press L, to open the Python Lab.

ROADMAP FOR THIS PART

Module 1Meet Python & Your First Program2.5 h
Module 2Variables, Data Types & Input3 h
Module 3Operators & Expressions2.5 h
Module 4Strings & f-strings3 h
Module 5Decisions: if, elif, else & match3 h
Module 6Loops: for, while & range3.5 h
PythonBefore we begin

How to Use This Part

Suggested teaching hours per module (Part 1)012342.5 hM13 hM22.5 hM33 hM43 hM53.5 hM6

Every module has

  1. 1
    A "Where is it used?" diagram of real projects
  2. 2
    Concept slides with code + terminal: press ▶ Run to watch the output appear
  3. 3
    Step-through animations: watch variables change line by line
  4. 4
    A Live Lab: edit the code and run real Python in the browser
  5. 5
    5 practice examples (Beginner to Advanced) with solutions
  6. 6
    An animated recap + quiz
Controls→ next, ← back, M menu, L Python Lab, F fullscreen. In the Lab, Ctrl+Enter runs the code.
Running PythonOutputs on the slides were produced by real Python 3, so they work offline. The Lab loads Python from the internet the first time (10-40 s). Offline? Use ⬇ .py and run the file in IDLE or VS Code (folder D:\python-practice).
MODULE 1

Meet Python & Your First Program

⏱ 2.5 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • What a program and a programming language are
  • Where Python is used in the real world
  • Installing Python, IDLE and VS Code
  • print(), comments and running a .py file
  • Reading error messages without fear

You will build

  • A welcome banner for a coaching centre
  • A Ranchi to Jamshedpur bus ticket
  • A school timetable printout
print()python hello.py>>> 2 + 3
Module 1Real-world use

Where Is This Used in Real Projects?

Pythonone language, many jobs🤖AI & ChatGPTtrain smart models📸Instagramweb backend (Django)📊Data & chartsbanks, cricket stats🚀Space & scienceNASA, ISRO research🎮GamesPygame, game tools⚙Automationoffice work in seconds

Real projects that use this

  • AI and machine learning: chatbots, face unlock, crop-disease apps for Jharkhand farmers
  • Websites: Instagram and many Indian start-ups run Python (Django / Flask) on the server
  • Data analysis: school results, shop sales, election and weather data turned into charts
  • Automation: rename 1,000 photos, make 500 certificates, send report emails automatically
  • Science, robots & IoT: Raspberry Pi projects, drones, lab experiments
Why learn it first?Python is one of the most popular programming languages in the world, and it is the most common first language taught in schools and colleges.
Module 1The big idea

What Is a Program? What Is Python?

Youwrite instructionsPythontranslates themComputerdoes the workprint("Hi")0110 1001 ...Hi
RememberA program is a list of instructions, like a recipe. The computer follows it exactly, step by step, from top to bottom.

Think of a recipe for chai

  1. 1
    Boil 1 cup water
  2. 2
    Add tea leaves and sugar
  3. 3
    Add milk, boil 2 minutes
  4. 4
    Strain and serve

A computer only understands 0s and 1s. Python is a language that lets us write instructions in nearly-English words. The Python interpreter translates them for the computer, one line at a time.

Fun factPython was created by Guido van Rossum and released in 1991. It is free and open source. The name comes from a comedy show, not the snake!
Module 1Why Python?

Python Is Short, Clear and Powerful

Same job, two languages

Hello.javaTXT
1public class Hello {
2 public static void main(String[] args) {
3 System.out.println("Hello Ranchi");
4 }
5}
hello.py  PY
1print("Hello Ranchi")
Lines needed to print one message0241Python5C5Java
📖

Easy to read

Looks almost like English. Great for beginners.
₹0

Free

Download free for Windows, Mac, Linux.
🔋

Batteries included

Thousands of ready-made libraries.
💼

Jobs

Used by start-ups, banks, IT companies, research labs.
In real projectsPython reads like instructions to a friend. if marks >= 33: print("Pass") is easy to understand even before you learn it.
Module 1Set up

Installing Python on Windows

  1. 1
    Open python.org/downloads in your browser
  2. 2
    Click Download Python 3.x (the big yellow button)
  3. 3
    Open the downloaded file
  4. 4
    Tick Add python.exe to PATH (very important)
  5. 5
    Click Install Now and wait
  6. 6
    Open Command Prompt and type python --version
Command Prompt
C:\Users\Student> python --version
Python 3.13.0
Python 3.13 (64-bit) Setup— ☐ ✕
Install Python 3.13 (64-bit)

Select Install Now to install Python with default settings.

➤ Install Now
C:\Users\Student\AppData\Local\Programs\Python
☑ Use admin privileges when installing py.exe
☑ Add python.exe to PATH ← tick this!
Common mistakeForgot to tick "Add to PATH"? Run the installer again, choose Modify, and tick it. On mobile you can practise with apps like Pydroid 3.
Module 1Two ways to run Python

The Python Shell (IDLE): Talk to Python Directly

After installing, open IDLE from the Start menu. The >>> sign is the prompt: Python is waiting for you. Type a line, press Enter, and Python answers immediately.

Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 7
>>>

Shell (interactive)

Type one line, get an answer at once. Best for quick tests and calculations. Nothing is saved.
.py

Script (.py file)

Write many lines in a file like hello.py, save it, run it again and again. Real programs are scripts.
RememberIn the shell you can see a value just by typing it. In a .py file you must use print() to show it.
Module 1Set up

Writing Scripts in VS Code (Recommended Editor)

hello.py - python-practice - Visual Studio Code— ☐ ✕
EXPLORER

📁 PYTHON-PRACTICE
  🐍 hello.py
  🐍 bill.py
hello.pyPY
1# My first Python program
2print("Hello, Ranchi!")
3print("I am learning Python")
TERMINAL
PS D:\python-practice> python hello.py
Hello, Ranchi!
I am learning Python
  1. 1
    Install VS Code from code.visualstudio.com
  2. 2
    Install the Python extension (by Microsoft)
  3. 3
    Make a folder D:\python-practice and open it (File → Open Folder)
  4. 4
    New file → save as hello.py (the .py ending matters)
  5. 5
    Type your code and save with Ctrl+S
  6. 6
    Click ▶ Run (top right) or type python hello.py in the terminal
In real projectsIDLE is fine for small programs. VS Code gives colours, auto-complete and error hints, the same tool used by professional developers.
Module 1Your first function

print(): Show Something on the Screen

printfunction name
(a built-in command)
(open bracket
"Namaste Ranchi!"the text to show
(a string, in quotes)
)close bracket
  • Text must be inside quotes: "..." or '...'
  • Numbers do not need quotes: print(42)
  • Python is case-sensitive: Print is an error, print is correct
  • Every print() starts a new line
Module 1print() in action

Printing Text, Numbers and Many Items

main.py  PY
1print("Welcome to BrainBit Infotech Pvt Ltd")
2print('Single quotes work too')
3print(2026)
4print(10 + 5)
5print("Ranchi", "Jharkhand", "India")
6print() # empty line
7print("Total:", 450, "rupees")
Terminal
C:\python-practice> python main.py
Welcome to BrainBit Infotech Pvt Ltd
Single quotes work too
2026
15
Ranchi Jharkhand India
 
Total: 450 rupees
,

Many items

Separate items with commas. Python puts a space between them automatically.
+

Maths inside print

print(10 + 5) works out the sum first, then prints 15.
↵

Empty print()

Prints a blank line. Useful to space out your output.
Common mistakeprint("10 + 5") prints the text 10 + 5, but print(10 + 5) prints 15. Quotes make it text!
Module 1Control the output

sep and end: Change the Separator and the Line Ending

main.py  PY
1print("Ranchi", "Hatia", "Namkum", sep=" -> ")
2print("2026", "10", "08", sep="-")
3
4print("Loading", end="")
5print(".", end="")
6print(".", end="")
7print(". done!")
8
9print("Name:", "Priya", sep="\t")
Terminal
C:\python-practice> python main.py
Ranchi -> Hatia -> Namkum
2026-10-08
Loading... done!
Name: Priya
OptionDefaultWhat it does
sep=" " (space)what goes between items
end="\n" (new line)what goes at the end of the line
Remember"\n" means new line and "\t" means tab (a big gap). These are called escape characters.
In real projectsDates like 2026-10-08 in reports and progress bars like Loading... in apps are built exactly this way.
Module 1Notes for humans

Comments: Notes That Python Ignores

main.py  PY
1# Program: Fee receipt for BrainBit Infotech Pvt Ltd
2# Author : Your Name Date: 08-10-2026
3
4print("FEE RECEIPT") # heading
5print("Course: Python") # course name
6# print("This line is switched off")
7print("Amount paid: 4500")
8
9"""
10A multi-line note (docstring).
11Used at the top of files and functions.
12"""
Terminal
C:\python-practice> python main.py
FEE RECEIPT
Course: Python
Amount paid: 4500
#

# single-line comment

Everything after # on that line is ignored by Python.
🔇

Switch code off

Put # in front of a line to test without deleting it (line 6).
"""

Triple-quoted note

Text between """ and """ is used as a multi-line note or docstring.
In real projectsIn company projects, comments explain why code exists. Your future self (and your team) will thank you.
Module 1Watch it run

How Python Runs Your Program: Top to Bottom

Press Next step. Python runs one line at a time, from top to bottom. Watch the output grow.

main.py  PY
1# Morning assembly announcement
2print("Good morning, students!")
3print("Today is Wednesday.")
4# this comment is skipped
5print("Python class at 10 AM")
6print("Lab", "2", sep=" ")
7print("Have a great day!")
Output
Module 1Errors are normal

Reading Error Messages: Python Tells You What Went Wrong

main.py  PY
1print("Fee is due on 10th")
2print("Pay at the office)
Terminal
C:\python-practice> python main.py
File "main.py", line 2
print("Pay at the office)
^
SyntaxError: unterminated string literal (detected at line 2)

How to read the red text

  1. 1
    File and line number: where the problem is (line 2)
  2. 2
    The ^ arrow: points at the exact spot
  3. 3
    The last line: error type + reason. Read this first!
ErrorUsual cause
SyntaxErrormissing quote, bracket or colon
NameErrorspelling mistake, or text without quotes
IndentationErrorextra spaces at the start of a line
TypeErrormixing types, e.g. text + number
RememberEvery programmer sees errors every day. An error message is a clue, not a punishment.
Module 1More errors

Three Errors Every Beginner Meets

e1.py  PY
1Print("Hello")
Terminal
C:\python-practice> python e1.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
Print("Hello")
^^^^^
NameError: name 'Print' is not defined. Did you mean: 'print'?

Fix: lower-case print. Python is case-sensitive.

e2.py  PY
1print(Ranchi)
Terminal
C:\python-practice> python e2.py
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(Ranchi)
^^^^^^
NameError: name 'Ranchi' is not defined

Fix: text needs quotes: print("Ranchi").

e3.py  PY
1print("Hi")
2 print("Bye")
Terminal
C:\python-practice> python e3.py
File "main.py", line 2
print("Bye")
IndentationError: unexpected indent

Fix: remove the spaces at the start of line 2.

Module 1Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
==============================
WELCOME TO PYTHON CLASS
==============================
Name : Your Name
School : Your School, Ranchi
Goal : Build my own app!
Your tasks
  1. Put your own name, school and goal
  2. Add a line that prints your favourite food in Jharkhand
  3. Use sep="-" to print the date as 08-10-2026
  4. Make a spelling mistake on purpose, run it, and read the error
PracticePractice 1 of 5

Coaching Centre Welcome Banner

BeginnerScenario. BrainBit Infotech Computer Centre wants a welcome banner printed on the screen when students open the attendance program.

Your tasks

  1. Print a line of 40 * symbols using "*" * 40
  2. Print the centre name, address and phone
  3. Print the line of stars again at the end
  4. Add one empty line between heading and address
🏢 Used in real projects: Banners and headings are printed at the start of command-line tools, billing software in shops and attendance systems.
practice_1_1.py  PY
1# Welcome banner for the attendance program
2print("*" * 40)
3print(" BRAINBIT INFOTECH COMPUTER CENTRE")
4print()
5print(" Main Road, Ranchi, Jharkhand")
6print(" Phone: 98765 43210")
7print("*" * 40)
8print(" Welcome! Please mark attendance.")
PracticePractice 2 of 5

Bus Ticket: Ranchi to Jamshedpur

EasyScenario. A bus booking counter at Ranchi ITI bus stand prints a simple ticket for each passenger.

Your tasks

  1. Print a border with "-" * 34
  2. Use commas to print label and value together
  3. Use sep=" -> " to print the route
  4. Print the fare using maths inside print: 280 + 20 (toll)
🏢 Used in real projects: Ticket counters, cinema booking systems and parking machines print receipts in exactly this way, with labels and values.
practice_1_2.py  PY
1print("-" * 34)
2print(" JHARKHAND TRAVELS")
3print("-" * 34)
4print("Route :", "Ranchi", "Jamshedpur", sep=" -> ")
5print("Date :", "08-10-2026")
6print("Seat :", 14)
7print("Fare : Rs", 280 + 20)
8print("-" * 34)
9print("Happy journey!")
PracticePractice 3 of 5

Student ID Card with Tabs and New Lines

IntermediateScenario. Make a neat student ID card using escape characters, all from one print statement.

Your tasks

  1. Use \n to move to a new line
  2. Use \t to line up the values
  3. Print everything with a single print()
  4. Bonus: add a blood group line
🏢 Used in real projects: Text reports, printed slips and SMS messages use \n and \t to arrange text in lines and columns.
practice_1_3.py  PY
1print("+----------------------------+\n"
2 "| DAV PUBLIC SCHOOL, RANCHI |\n"
3 "+----------------------------+\n"
4 "Name\t: Aman Kumar\n"
5 "Class\t: 8 B\n"
6 "Roll\t: 17\n"
7 "Blood\t: B+\n"
8 "+----------------------------+")
PracticePractice 4 of 5

Fix the Errors (Debugging Challenge)

ChallengingScenario. The school clerk wrote this notice program but it does not run. Find and fix four mistakes.

Your tasks

  1. Run the buggy code in the Lab and read the error
  2. Fix one error at a time and run again
  3. Match the expected output exactly
buggy_notice.py  PY
1print("Exam Notice)
2Print("Class 10 maths exam on Monday")
3print(Bring your admit card)
4 print("All the best!")
🏢 Used in real projects: Real developers spend a lot of time debugging. Reading the error, fixing one thing, and re-running is the professional habit.
practice_1_4.py  PY
1print("Exam Notice")
2print("Class 10 maths exam on Monday")
3print("Bring your admit card")
4print("All the best!")
PracticePractice 5 of 5

School Timetable Printout

AdvancedScenario. The class teacher wants Monday's timetable printed in neat columns for the notice board.

Your tasks

  1. Print a title and a line of = signs
  2. Use sep="\t" to make columns
  3. Print 5 periods with time and subject
  4. Use end="" to print the footer in two parts on one line
🏢 Used in real projects: Timetables, price lists and report tables in command-line tools and printed slips use tab-separated columns.
practice_1_5.py  PY
1print("CLASS 8 B - MONDAY TIMETABLE")
2print("=" * 34)
3print("Period", "Time", "Subject", sep="\t")
4print("1", "09:00", "Maths", sep="\t")
5print("2", "09:45", "Science", sep="\t")
6print("3", "10:30", "Computer (Python)", sep="\t")
7print("4", "11:15", "English", sep="\t")
8print("5", "12:00", "Hindi", sep="\t")
9print("=" * 34)
10print("Lunch break: ", end="")
11print("12:45 to 1:15")
Module 1Recap

Module 1 Recap & Quiz

What you learned

  • 1A program is a list of instructions; Python runs it top to bottom
  • 2Install Python with Add to PATH; use IDLE for quick tests, VS Code for projects
  • 3print() shows text (in quotes) and numbers; commas add spaces
  • 4sep= changes the gap between items, end= changes the line ending
  • 5# starts a comment; \n = new line, \t = tab
  • 6Read errors from the last line up: error type, then line number

Quick quiz

What does print("5 + 5") show?

Quotes make it text, so Python prints it exactly as written.

Which line is a comment?

Python comments start with #.

print("A", "B", sep="-") prints?

sep replaces the default space with "-".
MODULE 2

Variables, Data Types & Input

⏱ 3 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Variables: storing values with names
  • Naming rules and good names
  • Data types: int, float, str, bool and type()
  • Taking input from the user with input()
  • Converting types with int(), float() and str()

You will build

  • A student profile card
  • A rupee to dollar converter
  • A tea stall bill that asks the quantity
x = 5name = "Priya"type(3.5)
Module 2Real-world use

Where Is This Used in Real Projects?

variablesremember values🔐Login pageusername, password🛒Shopping carttotal, quantity🎮Gamesscore, lives, level🏫School appname, marks, class🏦Bank appbalance, account no🌦Weather appcity, temperature

Real projects that use this

  • Every app remembers things while it runs: your name, cart total, game score
  • Flipkart stores quantity and price in variables to calculate your bill
  • A school result system stores marks, then works out the percentage
  • input() is how a program asks the user for information, like a form
Module 2The big idea

A Variable Is a Named Box That Stores a Value

"Priya"studenttype: str14agetype: int92.5markstype: floatTruepassedtype: bool
marksvariable name
= assignment: "store in"
92.5the value

Read it like this

marks = 92.5 means "store 92.5 in a box called marks". Later you just say marks and Python gives you 92.5.

  • = does not mean "equals" here. It means "store this value"
  • The name goes on the left, the value on the right
  • You can change the value any time: the box keeps only the latest value
In real projectsVariables let you write a program once and use it with different values: a bill program works for any price.
Module 2Create and use

Creating, Printing and Changing Variables

main.py  PY
1student = "Priya Kumari"
2school = "St. Xavier's, Ranchi"
3age = 14
4marks = 92.5
5
6print(student, "studies at", school)
7print("Age:", age)
8print("Marks:", marks)
9
10age = 15 # birthday! the old value is replaced
11print("New age:", age)
Terminal
C:\python-practice> python main.py
Priya Kumari studies at St. Xavier's, Ranchi
Age: 14
Marks: 92.5
New age: 15
=

Store once, use many times

Line 6 uses student and school. No need to type the name again.
↻

Change the value

Line 10 puts 15 in the age box. The old 14 is gone.
Common mistakeNo quotes around a variable name! print("age") prints the word age, but print(age) prints 15.
Module 2Watch it change

Step Through: A Game Score Updating

Python always works out the right side first, then stores the answer in the variable on the left.

main.py  PY
1score = 0
2lives = 3
3print("Game start! Score:", score)
4
5score = score + 10 # collected a coin
6score = score + 50 # defeated a monster
7lives = lives - 1 # hit by a rock
8print("Score:", score, "Lives:", lives)
9
10level = "Hundru Falls"
11print("Next level:", level)
Output
Module 2Naming

Rules for Naming Variables

✔ Allowed

nametotal_marksage2_countcity_namepriceWithGst

✘ Not allowed

2agetotal marksmy-nameclassprice$for
RuleExample
Letters, digits and _ onlyroll_no, not roll-no
Cannot start with a digitclass8, not 8class
No spacesfirst_name
Not a Python keywordnot if, for, class, True
Case-sensitiveAge and age are different

Good names tell a story

x = 450
y = 18
What do x and y mean?
price = 450
gst_percent = 18
Clear without comments!
RememberPython programmers use snake_case: small letters with underscores, like total_amount. This style is part of PEP 8, the official Python style guide.

Python keywords: FalseNoneTrueandasbreakclassdefelifelseforifimportinisnotorreturnwhilewith

Module 2Data types

The 4 Basic Data Types

intwhole numbers
roll no, age, quantity
14   -5   2026
floatdecimal numbers
price, marks, temperature
92.5   3.14   -0.5
strtext (string)
name, city, message
"Ranchi"   'A'   "123"
boolyes / no
passed? logged in?
True   False
Common mistake"123" in quotes is text, not a number. True has a capital T and no quotes.

Ask Python: what type is this?

Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 8
Module 2Asking the user

input(): Let the User Type a Value

main.py  PY
1name = input("What is your name? ")
2city = input("Which city do you live in? ")
3print("Hello", name + "!")
4print("Welcome from", city)
Terminal
C:\python-practice> python main.py
What is your name? Riya
Which city do you live in? Ranchi
Hello Riya!
Welcome from Ranchi
Green text = what the user typed.
namestores the answer
=
inputwaits for typing
("Your name? ")the question
(prompt)
  1. 1
    Python shows the question and waits
  2. 2
    The user types and presses Enter
  3. 3
    What they typed is stored in the variable as a string
In real projectsEvery app form, from railway booking to exam registration, is input from the user. In a terminal program, input() does that job.
Module 2The #1 beginner trap

input() Always Gives You a String

main.py  PY
1price = input("Price of one pen: ")
2qty = input("How many pens? ")
3total = price * qty
4print("Total:", total)
Terminal
C:\python-practice> python main.py
Price of one pen: 10
How many pens? 3
Traceback (most recent call last):
File "main.py", line 3, in <module>
total = price * qty
~~~~~~^~~~~
TypeError: can't multiply sequence by non-int of type 'str'

The user typed numbers, but input() returned "10" and "3", which are text. You cannot multiply text by text, so Python stops with a TypeError.

Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 4
RememberConvert first: price = int(input("Price: ")). Next slide shows how.
Module 2Type conversion

int(), float() and str(): Change the Type

main.py  PY
1price = int(input("Price of one pen: "))
2qty = int(input("How many pens? "))
3total = price * qty
4print("Total: Rs", total)
5
6height = float(input("Your height in metres: "))
7print("Height in cm:", height * 100)
8
9message = "You owe Rs " + str(total)
10print(message)
Terminal
C:\python-practice> python main.py
Price of one pen: 10
How many pens? 3
Total: Rs 30
Your height in metres: 1.62
Height in cm: 162.0
You owe Rs 30
FunctionConverts toExampleResult
int()whole numberint("25")25
float()decimalfloat("1.62")1.62
str()textstr(30)'30'
int()drops decimalsint(9.99)9
Common mistakeint("abc") or int("12.5") crashes with a ValueError. In Module 13 you will learn to catch such errors.
Module 2Conversion map

Converting Between Types: What Works, What Breaks

"25"str25int25.0floatint("25")float("25")
RememberCheck with type() any time you are unsure what a variable holds.
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 9
Module 2Two at once

Multiple Assignment and Swapping Values

Python can fill several variables in one line. This is used everywhere, for example to swap two values or read x, y coordinates.

main.py  PY
1a, b = 5, 10 # two variables in one line
2print("Before:", a, b)
3
4a, b = b, a # swap!
5print("After:", a, b)
6
7x = y = z = 0 # same value to many
8score_ranchi, score_dhanbad = 245, 198
9print(score_ranchi, score_dhanbad)
Output
Module 2Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Name: Your Name | type: <class 'str'>
Age: 14 | type: <class 'int'>
Height: 152.5 | type: <class 'float'>
Likes Python? True
Age in 5 years: 19
Your tasks
  1. Change the values to your own details
  2. Replace name = "Your Name" with name = input("Name? ")
  3. Ask the age with int(input(...)) and print the age in 10 years
  4. Print age * 365: your approximate age in days
PracticePractice 1 of 5

Student Profile Card

BeginnerScenario. The school library software shows a profile card for each student. Store the details in variables and print them.

Your tasks

  1. Make variables: name, class_sec, roll_no, city, is_member
  2. Use the right type for each (str, int, bool)
  3. Print a neat card with labels
  4. Print the type of roll_no on the last line
🏢 Used in real projects: Every app stores user details in variables before showing them on a profile page or saving them in a database.
practice_2_1.py  PY
1name = "Ankit Oraon"
2class_sec = "9 A"
3roll_no = 21
4city = "Ranchi"
5is_member = True
6
7print("=" * 30)
8print(" LIBRARY PROFILE CARD")
9print("=" * 30)
10print("Name :", name)
11print("Class :", class_sec)
12print("Roll No :", roll_no)
13print("City :", city)
14print("Member? :", is_member)
15print("=" * 30)
16print("roll_no is of", type(roll_no))
PracticePractice 2 of 5

How Old Will You Be?

EasyScenario. A school admission form asks your birth year and tells you your age this year and in the year 2030.

Your tasks

  1. Ask the name with input()
  2. Ask the birth year and convert it with int()
  3. Calculate age in 2026 and in 2030
  4. Print a friendly message
🏢 Used in real projects: Age checks are used in admission portals, voter ID apps, insurance forms and OTT parental controls.
practice_2_2.py  PY
1name = input("Your name: ")
2birth_year = int(input("Year you were born: "))
3
4age_now = 2026 - birth_year
5age_2030 = 2030 - birth_year
6
7print("Hi", name + "!")
8print("In 2026 you turn", age_now)
9print("In 2030 you will be", age_2030)
PracticePractice 3 of 5

Rupee to Dollar Converter

IntermediateScenario. A travel agent in Ranchi converts rupees to US dollars for students going abroad. Use an example rate of Rs 84 = 1 USD.

Your tasks

  1. Store the rate in a variable usd_rate
  2. Ask the amount in rupees using float(input())
  3. Divide to get dollars and round to 2 decimals with round(x, 2)
  4. Also convert dollars back to rupees as a check
🏢 Used in real projects: Currency apps, banking apps and e-commerce sites selling abroad use the same formula with live exchange rates.
practice_2_3.py  PY
1usd_rate = 84.0 # example rate: Rs 84 = 1 US dollar
2
3rupees = float(input("Amount in rupees: "))
4dollars = round(rupees / usd_rate, 2)
5print("Rs", rupees, "=", "$", dollars)
6
7back = round(dollars * usd_rate, 2)
8print("Check:", dollars, "USD =", back, "rupees")
PracticePractice 4 of 5

Tea Stall Bill

ChallengingScenario. Raju's tea stall near Morhabadi sells tea for Rs 12 and samosa for Rs 15. Make a bill program that asks the quantities.

Your tasks

  1. Store the prices in variables
  2. Ask how many teas and samosas (convert to int)
  3. Calculate each item total and the grand total
  4. Print a neat bill with str() joining text and numbers
🏢 Used in real projects: Point-of-sale (POS) software in shops and restaurants does exactly this: price variables x quantity = bill.
practice_2_4.py  PY
1tea_price = 12
2samosa_price = 15
3
4teas = int(input("Cups of tea: "))
5samosas = int(input("Samosas: "))
6
7tea_total = teas * tea_price
8samosa_total = samosas * samosa_price
9grand = tea_total + samosa_total
10
11print("-" * 28)
12print("Tea x " + str(teas) + " = Rs " + str(tea_total))
13print("Samosa x " + str(samosas) + " = Rs " + str(samosa_total))
14print("-" * 28)
15print("TOTAL = Rs " + str(grand))
PracticePractice 5 of 5

Distance Unit Converter

AdvancedScenario. A cycling club records rides in kilometres. Convert one ride into metres, centimetres and miles, and work out the average speed.

Your tasks

  1. Ask the distance in km and the time in hours (both float)
  2. Convert km to m (x1000) and cm (x100000)
  3. Convert to miles (1 km = 0.621371 miles)
  4. Average speed = distance / time, rounded to 1 decimal
🏢 Used in real projects: Fitness apps like Strava and Google Fit convert units and calculate speed with exactly these formulas.
practice_2_5.py  PY
1km = float(input("Ride distance (km): "))
2hours = float(input("Time taken (hours): "))
3
4metres = km * 1000
5centimetres = km * 100000
6miles = round(km * 0.621371, 2)
7speed = round(km / hours, 1)
8
9print("Distance:", km, "km")
10print(" =", metres, "m")
11print(" =", centimetres, "cm")
12print(" =", miles, "miles")
13print("Average speed:", speed, "km/h")
Module 2Recap

Module 2 Recap & Quiz

What you learned

  • 1A variable is a named box: name = value stores the value
  • 2Names: letters, digits, _; no spaces; cannot start with a digit; use snake_case
  • 3Types: int (14), float (92.5), str ("Ranchi"), bool (True/False); check with type()
  • 4input() always returns a string
  • 5Convert with int(), float(), str() before doing maths
  • 6a, b = b, a swaps two values

Quick quiz

What is type("45")?

It is in quotes, so it is a string.

Which is a valid variable name?

Cannot start with a digit or contain spaces.

age = input("Age? ") and the user types 14. What is age?

input() always returns a string.
MODULE 3

Operators & Expressions

⏱ 2.5 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Arithmetic: + - * / // % **
  • Order of operations (BODMAS in Python)
  • Shortcut assignment: += -= *=
  • Comparison operators that give True / False
  • Logical operators: and, or, not

You will build

  • A GST bill calculator
  • A seconds to hours:minutes:seconds converter
  • A simple interest and EMI calculator
+ - * /17 // 52 ** 10
Module 3Real-world use

Where Is This Used in Real Projects?

operatorsdo the maths🧾BillingGST, discount🏦Loan appsEMI, interest⏰Clocks & timersseconds to h:m:s🎮Gamesspeed, gravity📊Resultspercentage, average🔒Loginsand / or checks

Real projects that use this

  • Every bill in a shop adds prices, applies discounts and GST with * and +
  • Banking apps calculate EMI and interest with ** (power)
  • Video players turn 3725 seconds into 1:02:05 using // and %
  • Login systems check username_ok and password_ok
Module 3Maths in Python

The 7 Arithmetic Operators

main.py  PY
1a = 17
2b = 5
3print("a + b =", a + b) # addition
4print("a - b =", a - b) # subtraction
5print("a * b =", a * b) # multiplication
6print("a / b =", a / b) # division (always float)
7print("a // b =", a // b) # floor division (whole part)
8print("a % b =", a % b) # modulus (remainder)
9print("a ** b =", a ** b) # power: 17 x 17 x 17 x 17 x 17
Terminal
C:\python-practice> python main.py
a + b = 22
a - b = 12
a * b = 85
a / b = 3.4
a // b = 3
a % b = 2
a ** b = 1419857
OpNameExampleResult
+add450 + 50500
-subtract500 - 120380
*multiply12 * 448
/divide10 / 42.5
//floor divide10 // 42
%remainder10 % 42
**power2 ** 38
Common mistake/ always gives a float: 10 / 2 is 5.0, not 5.
Module 3// and % explained

Floor Division and Remainder: Sharing Chocolates

friend 1friend 2friend 3friend 4friend 52 left over

17 chocolates, 5 friends. How many does each get, and how many are left?

Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 6
Use of %Example
Even or odd?n % 2 == 0 means even
Every 3rd itemi % 3 == 0
Minutes left over200 % 60 = 20
Module 3Order of operations

Precedence: Python Follows BODMAS

Watch Python solve 10 + 2 * (6 - 3) ** 2 / 3

10 + 2 * (6 - 3) ** 2 / 3Brackets first
10 + 2 * 3 ** 2 / 3then Power
10 + 2 * 9 / 3then * and / from left to right
10 + 18 / 3still left to right
10 + 6.0then + and -
16.0final answer (float because of /)
1 / 6
PriorityOperators
1 (highest)( ) brackets
2** power
3* / // %
4+ -
5== != < > <= >=
6not, then and, then or
RememberWhen in doubt, add brackets. (price + tax) * qty is clearer and safer than relying on rules.
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 3
Module 3Shortcuts

Assignment Operators: += -= *= /=

Updating a variable using its own value is so common that Python gives shortcuts. Used for counters, scores and running totals.

main.py  PY
1wallet = 500
2print("Pocket money:", wallet)
3wallet += 200 # same as wallet = wallet + 200
4wallet -= 150 # bought a book
5wallet *= 2 # Diwali bonus doubles it!
6wallet //= 3 # shared with 2 siblings
7print("Final:", wallet)
Output
Module 3Comparisons

Comparison Operators Give True or False

OperatorMeaningExampleResult
==equal to5 == 5True
!=not equal5 != 3True
>greater than40 > 33True
<less than20 < 33True
>=greater or equal33 >= 33True
<=less or equal34 <= 33False
Common mistake= stores a value. == asks a question: "are these equal?" Mixing them up is the most common beginner bug.
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 8
Module 3Combining conditions

Logical Operators: and, or, not

&

and: both must be True

Enter the exam hall if has_admit_card and on_time.
|

or: at least one True

Free entry if age < 5 or age > 60.
!

not: flips True / False

not is_blocked is True when the user is not blocked.
ABA and BA or Bnot A
TrueTrueTrueTrueFalse
TrueFalseFalseTrueFalse
FalseTrueFalseTrueTrue
FalseFalseFalseFalseTrue
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 8
Module 3Useful built-ins

round(), abs(), max(), min() and pow()

main.py  PY
1price = 399.456
2print(round(price)) # nearest whole number
3print(round(price, 2)) # 2 decimal places
4
5temp_change = -7
6print(abs(temp_change)) # distance from 0
7
8print(max(45, 78, 62)) # biggest
9print(min(45, 78, 62)) # smallest
10print(pow(2, 10)) # same as 2 ** 10
11print(10 ** 0.5) # square root of 10
Terminal
C:\python-practice> python main.py
399
399.46
7
78
45
1024
3.1622776601683795
≈

round(x, n)

Money is shown with 2 decimals: round(total, 2).
|x|

abs(x)

Difference between two temperatures or scores, ignoring the minus sign.
↕

max / min

Highest and lowest marks in a class, cheapest price.
Rememberx ** 0.5 is the square root. In Module 11 you will also see math.sqrt().
Module 3Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Subtotal : 3750
Discount : 375.0
GST : 607.5
TOTAL : 3982.5
Your tasks
  1. Change the price and quantity
  2. Make discount_percent 0 and check the total
  3. Ask the price and quantity using int(input())
  4. Print total > 5000 to see if free delivery applies
PracticePractice 1 of 5

GST Bill for a Mobile Shop

BeginnerScenario. A mobile accessories shop on Main Road, Ranchi adds 18% GST to every sale.

Your tasks

  1. Ask the item price (float)
  2. GST = price x 18 / 100
  3. Total = price + GST
  4. Print all three, rounded to 2 decimals
🏢 Used in real projects: Every billing app in India (Vyapar, Tally, Swiggy invoices) calculates GST exactly like this.
practice_3_1.py  PY
1price = float(input("Item price (Rs): "))
2gst_rate = 18
3
4gst = price * gst_rate / 100
5total = price + gst
6
7print("Price : Rs", round(price, 2))
8print("GST @ 18% : Rs", round(gst, 2))
9print("Total : Rs", round(total, 2))
PracticePractice 2 of 5

Split the Restaurant Bill

EasyScenario. Five friends ate litti chokha at a restaurant in Lalpur. Split the bill equally, with a 10% tip.

Your tasks

  1. Ask the bill amount and the number of friends
  2. Add a 10% tip
  3. Use / for exact share, // for whole rupees
  4. Use % to find the rupees left over
🏢 Used in real projects: Bill-splitting apps like Splitwise and UPI group payments use division and remainder.
practice_3_2.py  PY
1bill = int(input("Bill amount: "))
2friends = int(input("Number of friends: "))
3
4tip = bill * 10 // 100
5total = bill + tip
6exact_share = total / friends
7whole_share = total // friends
8left_over = total % friends
9
10print("Total with tip :", total)
11print("Exact share :", round(exact_share, 2))
12print("Each pays :", whole_share)
13print("Left over :", left_over, "(one friend pays this extra)")
PracticePractice 3 of 5

Seconds to Hours, Minutes and Seconds

IntermediateScenario. A YouTube-style video player needs to show the length of a video as H:M:S.

Your tasks

  1. Ask the total seconds
  2. Hours = seconds // 3600
  3. Minutes = (seconds % 3600) // 60
  4. Seconds left = seconds % 60
🏢 Used in real projects: Video players, cricket match timers, exam countdowns and parking meters all convert seconds this way.
practice_3_3.py  PY
1total = int(input("Video length in seconds: "))
2
3hours = total // 3600
4minutes = (total % 3600) // 60
5seconds = total % 60
6
7print(total, "seconds =", hours, "h", minutes, "min", seconds, "s")
PracticePractice 4 of 5

Pass or Fail with Booleans

ChallengingScenario. JAC board rules (example): a student passes if the total percentage is at least 33 and theory marks are at least 30% in the subject.

Your tasks

  1. Ask theory marks (out of 80) and practical marks (out of 20)
  2. Calculate the percentage of 100
  3. Make two boolean variables for the two rules
  4. Combine with and and print the result
🏢 Used in real projects: Result-processing software for boards and universities combines many rules with and / or.
practice_3_4.py  PY
1theory = int(input("Theory marks (out of 80): "))
2practical = int(input("Practical marks (out of 20): "))
3
4total = theory + practical
5percentage = total / 100 * 100
6theory_ok = theory >= 80 * 30 / 100
7overall_ok = percentage >= 33
8passed = theory_ok and overall_ok
9
10print("Percentage :", percentage)
11print("Theory OK :", theory_ok)
12print("Overall OK :", overall_ok)
13print("PASSED :", passed)
PracticePractice 5 of 5

Simple Interest and EMI Calculator

AdvancedScenario. A bank in Ranchi offers a two-wheeler loan. Calculate simple interest and the monthly EMI using the standard EMI formula.

Your tasks

  1. Ask principal, yearly rate (%) and years
  2. Simple interest = P x R x T / 100
  3. Monthly rate r = R / 12 / 100, months n = T x 12
  4. EMI = P x r x (1+r)n / ((1+r)n - 1)
🏢 Used in real projects: Loan and EMI calculators on bank websites, Bajaj Finserv and car showroom apps use this exact formula.
practice_3_5.py  PY
1P = float(input("Loan amount: "))
2R = float(input("Interest rate per year (%): "))
3T = int(input("Years: "))
4
5simple_interest = P * R * T / 100
6print("Simple interest :", round(simple_interest, 2))
7
8r = R / 12 / 100
9n = T * 12
10emi = P * r * (1 + r) ** n / ((1 + r) ** n - 1)
11print("Monthly EMI :", round(emi, 2))
12print("Total paid :", round(emi * n, 2))
13print("Total interest :", round(emi * n - P, 2))
Module 3Recap

Module 3 Recap & Quiz

What you learned

  • 1Arithmetic: + - * / // % **; / always gives a float
  • 2// gives the whole part, % gives the remainder
  • 3Precedence: brackets, then **, then * / // %, then + -
  • 4Shortcuts: x += 5 means x = x + 5
  • 5Comparisons == != > < >= <= give True or False
  • 6and (both), or (any), not (flip)

Quick quiz

What is 17 % 5?

17 = 5 x 3 + 2, so the remainder is 2.

What is 2 + 3 * 2?

* first: 3 x 2 = 6, then 2 + 6 = 8.

True and False gives?

and needs both sides to be True.
MODULE 4

Strings & f-strings

⏱ 3 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Creating strings, len(), joining and repeating
  • Indexing and slicing (positive and negative)
  • String methods: upper, strip, replace, split, find ...
  • f-strings for neat formatted output
  • Escape characters and the in operator

You will build

  • A username generator
  • Mobile number masking like banking apps
  • A formatted invoice line
"Hi"f"{name}"s[0:3]
Module 4Real-world use

Where Is This Used in Real Projects?

strtext everywhere👤Sign-up formsclean names, emails📱SMS & OTPmessage templates🔍Search barsmatch words🧾Invoicesneat formatting💬Chat appsemojis, mentions🗂Data cleaningfix messy text

Real projects that use this

  • Banking apps show your account as XXXXXX4521 using slicing
  • Sign-up forms remove extra spaces with strip() and check emails with "@" in email
  • SMS like "Dear Priya, your OTP is 4821" are made with f-strings
  • Search features use lower() so "RANCHI" matches "ranchi"
Module 4Making strings

Strings: Text in Quotes

main.py  PY
1city = "Ranchi"
2state = 'Jharkhand'
3quote = "It's the City of Waterfalls"
4address = """BrainBit Infotech Pvt Ltd
5Main Road, Ranchi
6Jharkhand - 834001"""
7
8print(city, state)
9print(quote)
10print(address)
11print(len(city)) # number of characters
12print(city + ", " + state) # join with +
13print("-" * 20) # repeat with *
Terminal
C:\python-practice> python main.py
Ranchi Jharkhand
It's the City of Waterfalls
BrainBit Infotech Pvt Ltd
Main Road, Ranchi
Jharkhand - 834001
6
Ranchi, Jharkhand
--------------------
""

Single or double quotes

Both work. Use double quotes when the text has an apostrophe: "It's".
"""

Triple quotes

For text over many lines, like an address or a letter.
#

len()

Counts characters, including spaces. len("Ranchi") is 6.
Common mistake"5" + "5" is "55", not 10. With strings, + joins.
Module 4Indexing

Every Character Has a Position (Index)

city = 'RANCHI'
0
R
-6
1
A
-5
2
N
-4
3
C
-3
4
H
-2
5
I
-1
city[ : : ]
RememberIndexes start at 0, not 1! The last character is at -1.
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 7
Common mistakeStrings are immutable: you cannot change one letter. Make a new string instead: "D" + city[1:].
Module 4Slicing

Slicing: Cut Out Part of a String

state = 'JHARKHAND'
0
J
-9
1
H
-8
2
A
-7
3
R
-6
4
K
-5
5
H
-4
6
A
-3
7
N
-2
8
D
-1
state[ : : ]

Change the numbers or click a preset. Green boxes are picked.

statethe string
[
startfirst index
(included)
:
stopstop index
(NOT included)
:
stepjump
(default 1)
]
SliceMeaningResult
state[0:5]index 0 to 4'JHARK'
state[5:]from 5 to the end'HAND'
state[:3]first 3'JHA'
state[-4:]last 4'HAND'
state[::-1]reversed'DNAHKRAHJ'
In real projectsGet the year from "08-10-2026" with date[-4:], or the first name initial with name[0].
Module 4String methods

String Methods: Built-in Tools for Text

MethodWhat it doesExample result
.upper()ALL CAPS'RANCHI'
.lower()all small'ranchi'
.title()Each Word Capital'Priya Kumari'
.strip()remove spaces at both ends'Priya'
.replace(a, b)swap text'Ranchi-834001'
.count(x)how many times2
.find(x)position (or -1)3
.startswith(x)True / FalseTrue
.isdigit()only digits?True
RememberMethods return a new string. name.upper() does not change name unless you store it: name = name.upper().
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 10
Module 4Split and join

split() and join(): Break Text Apart and Put It Together

main.py  PY
1line = "Aman,Class 9,Ranchi,92"
2parts = line.split(",")
3print(parts)
4print("Name:", parts[0])
5print("Marks:", parts[3])
6
7sentence = "Python is fun to learn"
8words = sentence.split() # split on spaces
9print(len(words), "words")
10
11print("-".join(["2026", "10", "08"]))
12print(" | ".join(words))
Terminal
C:\python-practice> python main.py
['Aman', 'Class 9', 'Ranchi', '92']
Name: Aman
Marks: 92
5 words
2026-10-08
Python | is | fun | to | learn
✂

split(sep)

Breaks a string into a list of pieces. With no argument it splits on spaces.
🔗

sep.join(list)

Glues the pieces together with sep between them.
In real projectsData files (CSV) store each row as "Aman,Class 9,Ranchi,92". split(",") is how programs read them. You will use this in Module 12.
Module 4f-strings

f-strings: The Best Way to Mix Text and Values

main.py  PY
1name = "Priya"
2marks = 456
3total = 500
4percent = marks / total * 100
5
6print(f"Hello {name}!")
7print(f"{name} scored {marks} out of {total}")
8print(f"Percentage: {percent:.2f}%")
9print(f"Next year you will be in class {8 + 1}")
10print(f"Fee: Rs {125000:,}")
Terminal
C:\python-practice> python main.py
Hello Priya!
Priya scored 456 out of 500
Percentage: 91.20%
Next year you will be in class 9
Fee: Rs 125,000
ff before the quote
"Hello normal text
{name}value goes here
!"
Inside { }Result
{percent:.2f}2 decimal places: 91.20
{125000:,}thousands commas: 125,000
{8 + 1}any expression: 9
RememberCompare: "Hi " + name + ", you scored " + str(marks) vs f"Hi {name}, you scored {marks}". f-strings need no str()!
Module 4Formatting columns

f-string Alignment: Neat Tables and Bills

main.py  PY
1print(f"{'Item':<12}{'Qty':>5}{'Price':>10}")
2print("-" * 27)
3print(f"{'Litti':<12}{4:>5}{60.0:>10.2f}")
4print(f"{'Chokha':<12}{2:>5}{40.5:>10.2f}")
5print(f"{'Lassi':<12}{3:>5}{90:>10.2f}")
6print("-" * 27)
7print(f"{'TOTAL':<12}{'':>5}{190.5:>10.2f}")
8print(f"{'*':^27}")
9print(f"{'Thank you!':*^27}")
Terminal
C:\python-practice> python main.py
Item Qty Price
---------------------------
Litti 4 60.00
Chokha 2 40.50
Lassi 3 90.00
---------------------------
TOTAL 190.50
*
********Thank you!*********
FormatMeaning
:<12left-align in 12 spaces
:>5right-align in 5 spaces
:^27centre in 27 spaces
:>10.2fright-align, 2 decimals
:*^27centre, fill with *
In real projectsThis is how command-line bills, bank statements and report tables line up perfectly.
Module 4Special characters

Escape Characters and the in Operator

main.py  PY
1print("Line 1\nLine 2") # \n new line
2print("Name:\tAman") # \t tab
3print("She said \"Hello\"") # \" quote inside quotes
4print("Path: C:\\python\\notes") # \\ one backslash
5print(r"Raw: C:\new\test") # r"..." raw string
6
7email = "priya@gmail.com"
8print("@" in email)
9print("yahoo" in email)
10print("xyz" not in email)
Terminal
C:\python-practice> python main.py
Line 1
Line 2
Name: Aman
She said "Hello"
Path: C:\python\notes
Raw: C:\new\test
True
False
True
CodeMeans
\nnew line
\ttab
\" \'quote inside a string
\\one backslash
r"..."raw: backslashes stay as they are
in

in / not in

Checks if some text is inside another string: True or False. Great for quick validation.
Module 4Watch the methods

Step Through: Cleaning a Messy Form Entry

Real sign-up forms receive messy text. Watch each method produce a new clean string.

main.py  PY
1raw = " aMAN kumar "
2clean = raw.strip()
3clean = clean.title()
4first = clean.split()[0]
5initials = clean[0] + "." + clean.split()[1][0] + "."
6username = first.lower() + "_" + str(len(clean))
7print(f"Welcome {clean}! Username: {username}")
Output
Module 4Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Name : Rahul Mahato
City : RANCHI
Mobile : 98XXXXXX10
Letters in name: 12
Reversed city: ihcnar
Your tasks
  1. Put your own name, city and number
  2. Print the first 3 letters of the city
  3. Count how many times "a" appears in your name
  4. Print your name centred in 30 characters with :^30
PracticePractice 1 of 5

Username Generator

BeginnerScenario. A coaching institute app creates usernames from the first name and birth year, e.g. riya2011.

Your tasks

  1. Ask full name and birth year
  2. Take the first word in lower case
  3. Join it with the birth year
  4. Print the username and its length
🏢 Used in real projects: Gmail, Instagram and college ERPs suggest usernames by combining name parts and numbers.
practice_4_1.py  PY
1full_name = input("Full name: ")
2year = input("Birth year: ")
3
4first = full_name.strip().split()[0].lower()
5username = first + year
6
7print(f"Your username: {username}")
8print(f"Length: {len(username)} characters")
PracticePractice 2 of 5

Mask a Mobile Number

EasyScenario. Banking SMS hide most digits of your number for safety: 98XXXXXX10.

Your tasks

  1. Ask the 10-digit mobile number
  2. Keep the first 2 and last 2 digits with slicing
  3. Put "X" * 6 in the middle
  4. Also mask an email: show the first 2 letters and the domain
🏢 Used in real projects: Banks, Aadhaar, UPI apps and e-commerce sites mask phone numbers, cards and emails exactly like this.
practice_4_2.py  PY
1mobile = input("Mobile number: ")
2masked = mobile[:2] + "X" * 6 + mobile[-2:]
3print("Mobile:", masked)
4
5email = input("Email: ")
6at = email.find("@")
7masked_email = email[:2] + "*" * (at - 2) + email[at:]
8print("Email :", masked_email)
PracticePractice 3 of 5

Word and Letter Counter

IntermediateScenario. A school magazine editor needs to check how long each student's paragraph is.

Your tasks

  1. Store a paragraph in a string
  2. Count words with split()
  3. Count characters with and without spaces
  4. Count how many times "the" appears (case-insensitive)
🏢 Used in real projects: Word counters in MS Word, Google Docs, Twitter/X character limits and SEO tools are built with split() and len().
practice_4_3.py  PY
1text = """The Hundru Falls is one of the highest waterfalls in Jharkhand.
2The Subarnarekha river falls from a height of about 98 metres."""
3
4words = text.split()
5no_spaces = text.replace(" ", "").replace("\n", "")
6
7print("Words :", len(words))
8print("Characters :", len(text))
9print("Characters (no gaps):", len(no_spaces))
10print("Times 'the' appears :", text.lower().split().count("the"))
PracticePractice 4 of 5

Format an Invoice

ChallengingScenario. Print a neat invoice for a stationery shop using f-string alignment.

Your tasks

  1. Store 3 item names, quantities and prices
  2. Print a header row with :< and :>
  3. Calculate each line total and the grand total
  4. Show money with 2 decimals and commas :,.2f
🏢 Used in real projects: Invoice generators, bank statements and receipt printers use fixed-width formatting so columns line up.
practice_4_4.py  PY
1shop = "Gupta Stationers, Ranchi"
2print(f"{shop:^40}")
3print("=" * 40)
4print(f"{'Item':<16}{'Qty':>5}{'Rate':>8}{'Amount':>11}")
5print("-" * 40)
6
7i1, q1, r1 = "Notebook", 12, 45.0
8i2, q2, r2 = "Gel pen (box)", 3, 120.0
9i3, q3, r3 = "Geometry box", 2, 1499.5
10
11print(f"{i1:<16}{q1:>5}{r1:>8.1f}{q1*r1:>11,.2f}")
12print(f"{i2:<16}{q2:>5}{r2:>8.1f}{q2*r2:>11,.2f}")
13print(f"{i3:<16}{q3:>5}{r3:>8.1f}{q3*r3:>11,.2f}")
14print("-" * 40)
15total = q1*r1 + q2*r2 + q3*r3
16print(f"{'GRAND TOTAL':<29}{total:>11,.2f}")
PracticePractice 5 of 5

PAN Number Format Checker

AdvancedScenario. A PAN card number has 10 characters: 5 letters, 4 digits, 1 letter (e.g. ABCDE1234F). Check the format using only string tools and booleans.

Your tasks

  1. Ask the PAN and clean it with strip().upper()
  2. Check length is 10
  3. Check pan[:5].isalpha(), pan[5:9].isdigit(), pan[9].isalpha()
  4. Combine with and and print the result
🏢 Used in real projects: KYC forms in banks, income-tax portals and fintech apps check PAN, IFSC and GST number formats before saving.
practice_4_5.py  PY
1pan = input("Enter PAN: ").strip().upper()
2
3length_ok = len(pan) == 10
4letters_ok = pan[:5].isalpha()
5digits_ok = pan[5:9].isdigit()
6last_ok = pan[9:].isalpha()
7
8print(f"Cleaned PAN : {pan}")
9print(f"Length 10 : {length_ok}")
10print(f"5 letters : {letters_ok}")
11print(f"4 digits : {digits_ok}")
12print(f"Last letter : {last_ok}")
13print(f"VALID FORMAT: {length_ok and letters_ok and digits_ok and last_ok}")
Module 4Recap

Module 4 Recap & Quiz

What you learned

  • 1Strings are text in quotes; len() counts characters; + joins, * repeats
  • 2Index from 0; negative index counts from the end (-1 = last)
  • 3Slice s[start:stop:step]; stop is not included; s[::-1] reverses
  • 4Methods return new strings: strip, upper, lower, title, replace, split, join, find
  • 5f-strings: f"Hi {name}"; format with :.2f, :,, :<10
  • 6\n new line, \t tab; "x" in s checks for text

Quick quiz

"PYTHON"[1:4] is?

Index 1, 2, 3 (stop 4 is not included).

" hi ".strip() gives?

strip removes spaces at both ends.

f"{3.14159:.2f}" gives?

.2f means 2 decimal places.
MODULE 5

Decisions: if, elif, else & match

⏱ 3 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • How a program makes decisions with if
  • if / else and the if / elif / else ladder
  • Indentation: how Python groups code
  • Nested ifs and combined conditions
  • Short if (ternary) and match-case

You will build

  • A JAC grade calculator
  • An electricity bill with slab rates
  • A login check and a restaurant menu
ifelif marks >= 60:else:
Module 5Real-world use

Where Is This Used in Real Projects?

if / elsechoose a path🔐Loginright password?🏧ATMenough balance?🎓Resultspass or fail🏷Offersdiscount if > Rs 999🚦Traffic signalred, yellow, green🗳Voting appage >= 18?

Real projects that use this

  • Swiggy and Zomato give free delivery if the order is above a limit
  • An ATM checks if balance >= amount, else shows "Insufficient funds"
  • Exam result software gives a grade with an if / elif ladder
  • Every login page checks if the password matches
Module 5if statement

if: Run Code Only When a Condition Is True

ifkeyword
marks >= 33condition
(True or False)
:colon is a must
if_demo.py  PY
1marks = 72
2if marks >= 33:
3 print("Pass") # indented = inside the if
4 print("Well done!")
5print("Result checked") # not indented = always runs
RememberPython uses indentation (4 spaces) to know which lines belong to the if. Other languages use { }. Python uses spaces.
marks = ?marks >= 33 ?TrueFalseprint("Pass")print("Fail")next line
Click a button to see which path Python takes.
Module 5if / else

if / else: Two Paths

main.py  PY
1age = int(input("Enter your age: "))
2
3if age >= 18:
4 print("You can vote in the Jharkhand elections.")
5 print("Bring your Voter ID card.")
6else:
7 years = 18 - age
8 print(f"Sorry, you can vote after {years} year(s).")
9
10print("Thank you for using the Voter Help app.")
Terminal
C:\python-practice> python main.py
Enter your age: 15
Sorry, you can vote after 3 year(s).
Thank you for using the Voter Help app.
else

else has no condition

It runs when the if condition is False. Exactly one of the two blocks runs.
⇥

Same indentation

All lines of a block must be indented the same: 4 spaces (VS Code inserts them when you press Tab).
Common mistakeMissing colon : or wrong indentation gives SyntaxError or IndentationError.
Module 5if / elif / else

The elif Ladder: Many Choices, One Answer

grade.py  PY
1marks = int(input("Marks: "))
2
3if marks >= 90:
4 grade = "A+"
5elif marks >= 75:
6 grade = "A"
7elif marks >= 60:
8 grade = "B"
9elif marks >= 33:
10 grade = "C"
11else:
12 grade = "F"
13
14print("Grade:", grade)
Click a button to see which path Python takes.
marks >= 90Truegrade = "A+"Falsemarks >= 75Truegrade = "A"Falsemarks >= 60Truegrade = "B"Falsemarks >= 33Truegrade = "C"Falsegrade = "F"
Module 5Watch it decide

Step Through: The Grade Program with marks = 81

Notice how Python skips the lines it does not need. Only one branch of the ladder runs.

main.py  PY
1marks = 81
2if marks >= 90:
3 grade = "A+"
4elif marks >= 75:
5 grade = "A"
6elif marks >= 60:
7 grade = "B"
8else:
9 grade = "F"
10print("Grade:", grade)
11if grade == "A+" or grade == "A":
12 print("Certificate of merit!")
Output
Module 5Nested if

Nested if: A Decision Inside a Decision

main.py  PY
1username = input("Username: ")
2password = input("Password: ")
3
4if username == "admin":
5 if password == "Ranchi@2026":
6 print("Login successful. Welcome, admin!")
7 else:
8 print("Wrong password. Try again.")
9else:
10 print("No such user.")
Terminal
C:\python-practice> python main.py
Username: admin
Password: ranchi
Wrong password. Try again.
  1. 1
    First check: is the username correct?
  2. 2
    Only then check the password (inner if, indented 8 spaces)
  3. 3
    Each else belongs to the if at the same indentation

Same logic, flatter code

flat.pyPY
1if username == "admin" and password == "Ranchi@2026":
2 print("Login successful")
3else:
4 print("Invalid username or password")
In real projectsReal websites say "Invalid username or password" without telling which one was wrong. That is safer: hackers cannot guess usernames.
Module 5Conditions

Writing Good Conditions: Ranges, and / or, Truthy Values

Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 9

Truthy and Falsy

Falsy (act like False)Truthy (act like True)
0, 0.0any other number
"" empty string"hello"
[] empty list[1, 2]
None, FalseTrue
empty_check.pyPY
1name = input("Name: ")
2if not name:
3 print("Name cannot be empty!")
Rememberif not name: is the Pythonic way to check for an empty input in forms.
Module 5Short form

Conditional Expression (Ternary): if / else in One Line

main.py  PY
1marks = 47
2result = "Pass" if marks >= 33 else "Fail"
3print(result)
4
5cart_total = 850
6delivery = 0 if cart_total >= 499 else 40
7print(f"Delivery charge: Rs {delivery}")
8
9n = 7
10print(f"{n} is", "even" if n % 2 == 0 else "odd")
Terminal
C:\python-practice> python main.py
Pass
Delivery charge: Rs 0
7 is odd
"Pass"value if True
if marks >= 33 condition
else "Fail"value if False
RememberUse the one-line form only for simple choices between two values. For anything longer, use a normal if / else.
In real projectsFree-delivery rules in shopping apps are often exactly this one line.
Module 5match-case (Python 3.10+)

match-case: Choose by Matching a Value

main.py  PY
1print("1. Litti Chokha 2. Dhuska 3. Pitha 4. Rugra curry")
2choice = input("Your choice: ")
3
4match choice:
5 case "1":
6 print("Litti Chokha: Rs 60")
7 case "2":
8 print("Dhuska with aloo: Rs 40")
9 case "3" | "4":
10 print("Seasonal special, ask the counter")
11 case _:
12 print("Invalid choice")
Terminal
C:\python-practice> python main.py
1. Litti Chokha 2. Dhuska 3. Pitha 4. Rugra curry
Your choice: 2
Dhuska with aloo: Rs 40
☰

match / case

Compares one value with many case patterns. Cleaner than a long elif chain for menus.
|

case "3" | "4"

The | means OR: either value matches.
_

case _

The underscore is the "anything else" case, like else.
Common mistakeNeeds Python 3.10 or newer. Check with python --version.
Module 5Avoid these

Top 5 Mistakes with if Statements

✘ Wrong

if marks = 33:
if marks >= 33
if x > 5:
print("big")

if city == "ranchi": (user typed Ranchi)
if a == 1 or 2:

✔ Right

if marks == 33:
if marks >= 33:
if x > 5:
    print("big")

if city.lower() == "ranchi":
if a == 1 or a == 2:
  1. 1
    = vs ==: one stores, two compares
  2. 2
    Missing colon at the end of if / elif / else
  3. 3
    No indentation inside the block
  4. 4
    Case: "Ranchi" != "ranchi"; use .lower()
  5. 5
    or with a bare value: a == 1 or 2 is always True!
Python Shell (IDLE / terminal)
# Python interactive shell. Press Next to type each line.
0 / 4
Module 5Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
Age: 10
Day (Mon/Tue/...): Tue
Tuesday offer: half price!
Ticket price: Rs 60
Your tasks
  1. Run it (the Lab asks your age and day in a small box)
  2. Add a new rule: students aged 12 to 18 pay Rs 180
  3. Make the day check work for "tue" and "TUE" too
  4. Print "Free entry!" when the price is 0
PracticePractice 1 of 5

JAC Board Grade Calculator

BeginnerScenario. Give a grade and a remark from the percentage. Grades: 90+ A+, 75+ A, 60+ B, 45+ C, 33+ D, below 33 F.

Your tasks

  1. Ask marks obtained and total marks
  2. Calculate the percentage
  3. Use if / elif / else to find the grade
  4. Print a remark: "Excellent" for A+, "Needs improvement" for F, else "Good"
🏢 Used in real projects: School ERPs, university result portals and online test platforms convert marks to grades with elif ladders.
practice_5_1.py  PY
1obtained = int(input("Marks obtained: "))
2total = int(input("Total marks: "))
3percent = obtained / total * 100
4
5if percent >= 90:
6 grade = "A+"
7elif percent >= 75:
8 grade = "A"
9elif percent >= 60:
10 grade = "B"
11elif percent >= 45:
12 grade = "C"
13elif percent >= 33:
14 grade = "D"
15else:
16 grade = "F"
17
18if grade == "A+":
19 remark = "Excellent"
20elif grade == "F":
21 remark = "Needs improvement"
22else:
23 remark = "Good"
24
25print(f"Percentage : {percent:.2f}%")
26print(f"Grade : {grade}")
27print(f"Remark : {remark}")
PracticePractice 2 of 5

Electricity Bill with Slab Rates

EasyScenario. Use example slab rates for a home connection: first 100 units Rs 6.30 each, next 100 units Rs 6.70, above 200 units Rs 7.40. Add a fixed charge of Rs 75.

Your tasks

  1. Ask the units consumed
  2. Use if / elif / else to apply the slabs
  3. Add the fixed charge
  4. Print the total and the average cost per unit
🏢 Used in real projects: Electricity, water and mobile data billing systems apply slab rates with if / elif conditions.
practice_5_2.py  PY
1units = int(input("Units consumed: "))
2
3if units <= 100:
4 energy = units * 6.30
5elif units <= 200:
6 energy = 100 * 6.30 + (units - 100) * 6.70
7else:
8 energy = 100 * 6.30 + 100 * 6.70 + (units - 200) * 7.40
9
10fixed = 75
11total = energy + fixed
12print(f"Energy charge : Rs {energy:,.2f}")
13print(f"Fixed charge : Rs {fixed:,.2f}")
14print(f"Total bill : Rs {total:,.2f}")
15print(f"Average/unit : Rs {total / units:.2f}")
PracticePractice 3 of 5

Login with Username and Password

IntermediateScenario. A school ERP lets the teacher log in. The username is case-insensitive, the password is not.

Your tasks

  1. Store the correct username and password
  2. Ask both, clean the username with strip().lower()
  3. Check both with and
  4. Give a separate hint if the password is too short (less than 8)
🏢 Used in real projects: Every login system (school ERP, Gmail, net banking) validates input and compares credentials with if / else.
practice_5_3.py  PY
1CORRECT_USER = "teacher01"
2CORRECT_PASS = "Dav#Ranchi9"
3
4user = input("Username: ").strip().lower()
5pwd = input("Password: ")
6
7if len(pwd) < 8:
8 print("Password must have at least 8 characters.")
9elif user == CORRECT_USER and pwd == CORRECT_PASS:
10 print(f"Welcome, {user}! You are logged in.")
11else:
12 print("Invalid username or password.")
PracticePractice 4 of 5

Bus Fare by Age and Distance

ChallengingScenario. Jharkhand Travels charges Rs 2 per km. Children under 5 travel free, children 5-12 pay half, seniors 60+ get 25% off. Night buses (after 9 PM) add Rs 50.

Your tasks

  1. Ask age, distance (km) and departure hour (0-23)
  2. Base fare = distance x 2
  3. Apply the age rules with if / elif / else
  4. Add the night charge with a one-line if
🏢 Used in real projects: Railway (IRCTC), bus and airline booking systems calculate fares with many if conditions: age, class, time and route.
practice_5_4.py  PY
1age = int(input("Passenger age: "))
2km = int(input("Distance (km): "))
3hour = int(input("Departure hour (0-23): "))
4
5fare = km * 2
6if age < 5:
7 fare = 0
8 category = "Infant (free)"
9elif age <= 12:
10 fare = fare / 2
11 category = "Child (half)"
12elif age >= 60:
13 fare = fare * 0.75
14 category = "Senior (25% off)"
15else:
16 category = "Adult"
17
18night = 50 if hour >= 21 and fare > 0 else 0
19total = fare + night
20print(f"Category : {category}")
21print(f"Fare : Rs {fare:.2f}")
22print(f"Night : Rs {night}")
23print(f"TOTAL : Rs {total:.2f}")
PracticePractice 5 of 5

Restaurant Menu with match-case

AdvancedScenario. A food court kiosk takes an order number and quantity, then shows the bill. Orders over Rs 300 get 10% off.

Your tasks

  1. Print a menu of 4 items
  2. Use match-case to set the item name and price
  3. Handle an invalid choice with case _
  4. Apply the discount with if and print the bill
🏢 Used in real projects: Self-order kiosks, IVR phone menus ("press 1 for...") and chatbots map choices to actions like this.
practice_5_5.py  PY
1print("1) Veg Thali Rs 120 2) Paneer Roll Rs 90")
2print("3) Chowmein Rs 80 4) Lassi Rs 50")
3choice = input("Order number: ")
4qty = int(input("Quantity: "))
5
6match choice:
7 case "1":
8 item, price = "Veg Thali", 120
9 case "2":
10 item, price = "Paneer Roll", 90
11 case "3":
12 item, price = "Chowmein", 80
13 case "4":
14 item, price = "Lassi", 50
15 case _:
16 item, price = None, 0
17
18if item is None:
19 print("Invalid order number!")
20else:
21 bill = price * qty
22 if bill > 300:
23 bill = bill * 0.9
24 print("10% discount applied")
25 print(f"{qty} x {item} = Rs {bill:.2f}")
Module 5Recap

Module 5 Recap & Quiz

What you learned

  • 1if condition: runs the indented block only when the condition is True
  • 2else: runs when it is False; elif checks more conditions in order
  • 3Only the first True branch of an if / elif / else ladder runs
  • 4Indentation (4 spaces) defines blocks; the colon : is required
  • 5Combine with and / or / not; check ranges like 18 <= age <= 60
  • 6One-line: x if cond else y; menus: match / case

Quick quiz

if x = 5: is wrong because...

= stores a value; == compares.

marks = 80. Which runs? if marks>=60: A elif marks>=75: B

The first True condition wins: 80 >= 60.

bool("") is?

An empty string is falsy.
MODULE 6

Loops: for, while & range

⏱ 3.5 hours5 practice examplesStep-through animationsPython Lab

You will learn

  • Why loops save time
  • for loops with range() and over strings
  • while loops and when to use them
  • break, continue and loop else
  • Nested loops and patterns

You will build

  • A multiplication table
  • A number guessing game
  • An ATM PIN check with 3 tries
forrange(1, 11)while True:
Module 6Real-world use

Where Is This Used in Real Projects?

loopsrepeat work📩Bulk SMSsend to 500 parents📦Ordersprocess each order🎮Game loopruns 60 times / sec🏧ATM3 PIN attempts📋Reportsone row per student📈Chartsone bar per month

Real projects that use this

  • A school sends an SMS to every parent using one loop, not 500 lines of code
  • Amazon processes each item in your cart in a loop to find the total
  • Every video game runs a while loop: read keys, move, draw, repeat
  • An ATM keeps asking for the PIN while attempts are left
Module 6Why loops?

Without a Loop vs With a Loop

main.py  PY
1print("Without a loop:")
2print("Welcome, student 1")
3print("Welcome, student 2")
4print("Welcome, student 3")
5
6print("With a loop:")
7for n in range(1, 6):
8 print("Welcome, student", n)
Terminal
C:\python-practice> python main.py
Without a loop:
Welcome, student 1
Welcome, student 2
Welcome, student 3
With a loop:
Welcome, student 1
Welcome, student 2
Welcome, student 3
Welcome, student 4
Welcome, student 5

Without a loop

100 students = 100 print lines. Need a change? Edit 100 lines!

With a loop

100 students = 2 lines. Change range(1, 101) and done.
RememberDRY = Don't Repeat Yourself. When you copy-paste the same line again and again, a loop is the answer.
start loopmore items?Yesrun the loop bodygo backNoafter the loop
Module 6range()

range(): A Ready-Made List of Numbers

Rememberstop is never included. range(1, 11) gives 1 to 10.
CodeNumbersUse for
range(5)0 1 2 3 4repeat 5 times
range(1, 6)1 2 3 4 5counting from 1
range(2, 21, 2)2 4 6 ... 20even numbers
range(10, 0, -1)10 9 ... 1countdown
range(0, 101, 25)0 25 50 75 100progress steps
forkeyword
i loop variable
(changes each time)
in
range(1, 6)what to loop over
:colon
Module 6Watch the loop

Step Through: Adding Up Monthly Savings

Watch how month takes the values 1, 2, 3, 4 and how total grows. This "running total" pattern is everywhere.

main.py  PY
1total = 0
2for month in range(1, 5):
3 saved = month * 100
4 total = total + saved
5 print(f"Month {month}: saved {saved}, total {total}")
6print("Final total:", total)
Output
Module 6Loop over anything

for Loops Work on Strings, Lists and More

main.py  PY
1for letter in "RANCHI":
2 print(letter, end=" ")
3print()
4
5cities = ["Ranchi", "Dhanbad", "Bokaro", "Jamshedpur"]
6for city in cities:
7 print("Sending parcel to", city)
8
9for i, city in enumerate(cities, start=1):
10 print(i, city)
Terminal
C:\python-practice> python main.py
R A N C H I
Sending parcel to Ranchi
Sending parcel to Dhanbad
Sending parcel to Bokaro
Sending parcel to Jamshedpur
1 Ranchi
2 Dhanbad
3 Bokaro
4 Jamshedpur
↻

for item in sequence

Python gives you each item one by one. No index counting needed.
1.

enumerate()

Gives the position and the item: perfect for numbered lists.
RememberYou will learn lists properly in Module 7. For now: a list is many values inside [ ].
Module 6while loop

while: Repeat As Long As a Condition Is True

main.py  PY
1countdown = 5
2while countdown > 0:
3 print(countdown, "...")
4 countdown -= 1
5print("Lift off! Chandrayaan launched!")
6
7balance = 1000
8months = 0
9while balance < 2000:
10 balance = balance * 1.10 # 10% growth
11 months += 1
12print(f"Doubled after {months} months: Rs {balance:.2f}")
Terminal
C:\python-practice> python main.py
5 ...
4 ...
3 ...
2 ...
1 ...
Lift off! Chandrayaan launched!
Doubled after 8 months: Rs 2143.59
UseWhen
foryou know how many times or have a collection
whileyou repeat until something happens (unknown count)
Common mistakeForgetting countdown -= 1 makes an infinite loop: the condition never becomes False. Press Ctrl+C to stop a stuck program.
Module 6break and continue

break (Stop the Loop) and continue (Skip to Next)

main.py  PY
1print("Searching roll numbers...")
2for roll in range(1, 11):
3 if roll == 4:
4 print(roll, "is absent - skip")
5 continue # jump to the next roll
6 if roll == 7:
7 print("Found topper at roll", roll, "- stop searching")
8 break # leave the loop completely
9 print("Checked roll", roll)
10print("Search finished")
Terminal
C:\python-practice> python main.py
Searching roll numbers...
Checked roll 1
Checked roll 2
Checked roll 3
4 is absent - skip
Checked roll 5
Checked roll 6
Found topper at roll 7 - stop searching
Search finished
↷

continue

Skips the rest of this round and goes to the next item.
⛔

break

Exits the loop immediately. Lines after the loop continue.
In real projectsSearch features use break: once the item is found, there is no need to check the rest.
Module 6Loop menu pattern

while True + break: The Menu Pattern Used in Real Apps

main.py  PY
1balance = 5000
2while True:
3 print("\n1. Balance 2. Withdraw 3. Exit")
4 choice = input("Choose: ")
5 if choice == "1":
6 print("Balance: Rs", balance)
7 elif choice == "2":
8 amount = int(input("Amount: "))
9 if amount <= balance:
10 balance -= amount
11 print("Please collect Rs", amount)
12 else:
13 print("Insufficient balance")
14 elif choice == "3":
15 print("Thank you for banking with us!")
16 break
17 else:
18 print("Invalid choice")
Terminal
C:\python-practice> python main.py
 
1. Balance 2. Withdraw 3. Exit
Choose: 1
Balance: Rs 5000
 
1. Balance 2. Withdraw 3. Exit
Choose: 2
Amount: 1500
Please collect Rs 1500
 
1. Balance 2. Withdraw 3. Exit
Choose: 2
Amount: 9000
Insufficient balance
 
1. Balance 2. Withdraw 3. Exit
Choose: 3
Thank you for banking with us!
  1. 1
    while True repeats forever...
  2. 2
    ...until the user chooses Exit and break runs
  3. 3
    Each round shows the menu and handles one choice
In real projectsATMs, ticket machines, command-line tools and chatbots all run a loop like this.
Module 6Nested loops

Loops Inside Loops: Tables and Patterns

main.py  PY
1for row in range(1, 5):
2 for col in range(1, row + 1):
3 print("*", end=" ")
4 print()
5
6print()
7for table in range(2, 4):
8 for i in range(1, 4):
9 print(f"{table} x {i} = {table * i}", end=" ")
10 print()
Terminal
C:\python-practice> python main.py
*
* *
* * *
* * * *
 
2 x 1 = 2 2 x 2 = 4 2 x 3 = 6
3 x 1 = 3 3 x 2 = 6 3 x 3 = 9

The inner loop runs completely for each round of the outer loop. Row 1 prints 1 star, row 2 prints 2 stars...

rowinner loopprints
1col = 1*
2col = 1, 2* *
3col = 1, 2, 3* * *
4col = 1..4* * * *
In real projectsNested loops build seating charts, calendars, game boards and every row x column table.
Module 6Watch nested loops

Step Through: A 3 x 2 Seating Chart

The inner loop finishes all its rounds (A, B) before the outer loop moves to the next row.

main.py  PY
1for row in range(1, 4):
2 for seat in "AB":
3 print(f"{row}{seat}", end=" ")
4 print()
5print("All seats printed")
Output
Module 6Hands-on

Live Lab: Try It Yourself

lab.py
Output Ready
Output of the starter code (press Run after you change it):
*
* *
* * *
* * * *
* * * * *
1 3 5 7 9
Sum of 1 to 100 = 5050
Your tasks
  1. Change n to 8 and run
  2. Print only multiples of 3 between 1 and 30
  3. Print a countdown from 10 to 1 using range(10, 0, -1)
  4. Use a while loop to find the first number whose square is more than 500
PracticePractice 1 of 5

Multiplication Table Printer

BeginnerScenario. A primary school teacher in Ranchi wants any multiplication table printed neatly for students.

Your tasks

  1. Ask which table to print
  2. Use for i in range(1, 11)
  3. Use an f-string with alignment for neat columns
  4. Print the sum of all values at the end
🏢 Used in real projects: Report generators, invoice line items and data exports print one row per loop round.
practice_6_1.py  PY
1n = int(input("Which table? "))
2total = 0
3print(f"--- Table of {n} ---")
4for i in range(1, 11):
5 result = n * i
6 total += result
7 print(f"{n:>3} x {i:>2} = {result:>4}")
8print(f"Sum of all results: {total}")
PracticePractice 2 of 5

Number Guessing Game

EasyScenario. Build a game: the computer picks a secret number from 1 to 50. The player gets hints until they guess it.

Your tasks

  1. Use random.randint(1, 50) for the secret (import random at the top)
  2. Loop with while until the guess is right
  3. Print "Too high" / "Too low" hints
  4. Count the attempts
🏢 Used in real projects: Games use loops plus random numbers; the same pattern is used in OTP retry screens and quiz apps.
practice_6_2.py  PY
1import random
2secret = random.randint(1, 50)
3attempts = 0
4guess = 0
5print("I am thinking of a number from 1 to 50...")
6
7while guess != secret:
8 guess = int(input("Your guess: "))
9 attempts += 1
10 if guess > secret:
11 print("Too high!")
12 elif guess < secret:
13 print("Too low!")
14
15print(f"Correct! It was {secret}. You took {attempts} attempts.")
PracticePractice 3 of 5

ATM PIN with 3 Attempts

IntermediateScenario. The ATM card is blocked after 3 wrong PIN attempts. Use a loop with break and the loop else.

Your tasks

  1. Store the correct PIN
  2. Loop for attempt in range(1, 4)
  3. break when the PIN is correct
  4. Use else: on the for loop to block the card when all 3 attempts fail
🏢 Used in real projects: ATMs, UPI apps and phone lock screens limit attempts with exactly this loop + break + else pattern.
practice_6_3.py  PY
1CORRECT_PIN = "4826"
2
3for attempt in range(1, 4):
4 pin = input(f"Attempt {attempt}/3 - Enter PIN: ")
5 if pin == CORRECT_PIN:
6 print("PIN accepted. Welcome!")
7 break
8 else:
9 left = 3 - attempt
10 print(f"Wrong PIN. {left} attempt(s) left.")
11else:
12 print("Card blocked! Please contact your bank branch.")
PracticePractice 4 of 5

Star Patterns: Pyramid and Diamond

ChallengingScenario. Printed patterns train your loop thinking. Make a pyramid and a diamond of a given height.

Your tasks

  1. Ask the height
  2. For each row print spaces " " * (h - i) then stars
  3. Make the pyramid, then reverse the loop for the bottom half
  4. Use range(h - 1, 0, -1) to go back down
🏢 Used in real projects: The same row-by-row thinking draws game boards, progress bars, charts and calendar grids.
practice_6_4.py  PY
1h = int(input("Height: "))
2
3print("Pyramid")
4for i in range(1, h + 1):
5 print(" " * (h - i) + "*" * (2 * i - 1))
6
7print("Diamond")
8for i in range(1, h + 1):
9 print(" " * (h - i) + "*" * (2 * i - 1))
10for i in range(h - 1, 0, -1):
11 print(" " * (h - i) + "*" * (2 * i - 1))
PracticePractice 5 of 5

Savings Goal Tracker

AdvancedScenario. Neha saves for a Rs 15,000 laptop. She starts with Rs 1,000 a month and increases her saving by Rs 200 every month. The bank adds 0.5% interest each month.

Your tasks

  1. Use a while loop until savings reach the goal
  2. Each month: add interest, then add the deposit
  3. Increase the deposit by 200 after each month
  4. Print a table row each month and the final month count
🏢 Used in real projects: Banking, SIP and loan apps simulate month-by-month growth with while loops to show when you reach a goal.
practice_6_5.py  PY
1goal = 15000
2savings = 0
3deposit = 1000
4month = 0
5print(f"{'Month':>5} {'Deposit':>8} {'Savings':>10}")
6while savings < goal:
7 month += 1
8 savings = savings * 1.005 + deposit
9 print(f"{month:>5} {deposit:>8} {savings:>10,.2f}")
10 deposit += 200
11print(f"Goal reached in {month} months!")
Module 6Recap

Module 6 Recap & Quiz

What you learned

  • 1Loops repeat code; DRY: do not repeat yourself
  • 2for x in range(a, b, step): stop b is not included
  • 3for works on strings, lists, ranges; enumerate() adds numbering
  • 4while condition: repeats until the condition is False; update the variable!
  • 5break exits, continue skips to the next round, loop else runs if no break
  • 6Nested loops: the inner loop runs fully for each outer round

Quick quiz

How many times does for i in range(2, 8): run?

2, 3, 4, 5, 6, 7: six times.

Which keyword skips to the next round?

continue skips the rest of this round.

while x > 0: with no change to x causes...

The condition never becomes False.
PART 1 COMPLETE

Well done!

You finished Python Foundations: 6 modules and 30 practice examples.

Before moving on

  • Re-type every practice example yourself without looking
  • Save your work in D:\python-practice\part1
  • Try the quizzes again until you get all of them right
  • Change one thing in each example and predict the output before you run it
print("Hi") >>> _
🐍 Python LabReady
Edit the code, then press Run. input() opens a small box to type your answer.
Terminal