Write your first programs: print, variables, input, operators, strings, decisions and loops.
Every code example has a ▶ Run button. Click ✎ Edit & Run, or press L, to open the Python Lab.
D:\python-practice).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.
1public class Hello {2 public static void main(String[] args) {3 System.out.println("Hello Ranchi");4 }5}
1print("Hello Ranchi")
if marks >= 33: print("Pass") is easy to understand even before you learn it.python --versionSelect Install Now to install Python with default settings.
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.
hello.py, save it, run it again and again. Real programs are scripts.print() to show it.1# My first Python program2print("Hello, Ranchi!")3print("I am learning Python")
D:\python-practice and open it (File → Open Folder)hello.py (the .py ending matters)python hello.py in the terminal"..." or '...'print(42)Print is an error, print is correctprint() starts a new line1print("Welcome to BrainBit Infotech Pvt Ltd")2print('Single quotes work too')3print(2026)4print(10 + 5)5print("Ranchi", "Jharkhand", "India")6print() # empty line7print("Total:", 450, "rupees")
print(10 + 5) works out the sum first, then prints 15.print("10 + 5") prints the text 10 + 5, but print(10 + 5) prints 15. Quotes make it text!1print("Ranchi", "Hatia", "Namkum", sep=" -> ")2print("2026", "10", "08", sep="-")34print("Loading", end="")5print(".", end="")6print(".", end="")7print(". done!")89print("Name:", "Priya", sep="\t")
| Option | Default | What it does |
|---|---|---|
sep= | " " (space) | what goes between items |
end= | "\n" (new line) | what goes at the end of the line |
"\n" means new line and "\t" means tab (a big gap). These are called escape characters.1# Program: Fee receipt for BrainBit Infotech Pvt Ltd2# Author : Your Name Date: 08-10-202634print("FEE RECEIPT") # heading5print("Course: Python") # course name6# print("This line is switched off")7print("Amount paid: 4500")89"""10A multi-line note (docstring).11Used at the top of files and functions.12"""
# on that line is ignored by Python.# in front of a line to test without deleting it (line 6).""" and """ is used as a multi-line note or docstring.Press Next step. Python runs one line at a time, from top to bottom. Watch the output grow.
1# Morning assembly announcement2print("Good morning, students!")3print("Today is Wednesday.")4# this comment is skipped5print("Python class at 10 AM")6print("Lab", "2", sep=" ")7print("Have a great day!")
1print("Fee is due on 10th")2print("Pay at the office)
| Error | Usual cause |
|---|---|
SyntaxError | missing quote, bracket or colon |
NameError | spelling mistake, or text without quotes |
IndentationError | extra spaces at the start of a line |
TypeError | mixing types, e.g. text + number |
1Print("Hello")
Fix: lower-case print. Python is case-sensitive.
1print(Ranchi)
Fix: text needs quotes: print("Ranchi").
1print("Hi")2 print("Bye")
Fix: remove the spaces at the start of line 2.
sep="-" to print the date as 08-10-2026* symbols using "*" * 401# Welcome banner for the attendance program2print("*" * 40)3print(" BRAINBIT INFOTECH COMPUTER CENTRE")4print()5print(" Main Road, Ranchi, Jharkhand")6print(" Phone: 98765 43210")7print("*" * 40)8print(" Welcome! Please mark attendance.")
"-" * 34sep=" -> " to print the route1print("-" * 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!")
\n to move to a new line\t to line up the valuesprint()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 "+----------------------------+")
1print("Exam Notice)2Print("Class 10 maths exam on Monday")3print(Bring your admit card)4 print("All the best!")
1print("Exam Notice")2print("Class 10 maths exam on Monday")3print("Bring your admit card")4print("All the best!")
= signssep="\t" to make columnsend="" to print the footer in two parts on one line1print("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")
print() shows text (in quotes) and numbers; commas add spacessep= changes the gap between items, end= changes the line ending# starts a comment; \n = new line, \t = tabWhat does print("5 + 5") show?
Which line is a comment?
print("A", "B", sep="-") prints?
quantity and price in variables to calculate your billmarks, then works out the percentageinput() is how a program asks the user for information, like a formmarks = 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"1student = "Priya Kumari"2school = "St. Xavier's, Ranchi"3age = 144marks = 92.556print(student, "studies at", school)7print("Age:", age)8print("Marks:", marks)910age = 15 # birthday! the old value is replaced11print("New age:", age)
student and school. No need to type the name again.age box. The old 14 is gone.print("age") prints the word age, but print(age) prints 15.Python always works out the right side first, then stores the answer in the variable on the left.
1score = 02lives = 33print("Game start! Score:", score)45score = score + 10 # collected a coin6score = score + 50 # defeated a monster7lives = lives - 1 # hit by a rock8print("Score:", score, "Lives:", lives)910level = "Hundru Falls"11print("Next level:", level)
| Rule | Example |
|---|---|
| Letters, digits and _ only | roll_no, not roll-no |
| Cannot start with a digit | class8, not 8class |
| No spaces | first_name |
| Not a Python keyword | not if, for, class, True |
| Case-sensitive | Age and age are different |
x = 450y = 18price = 450gst_percent = 18total_amount. This style is part of PEP 8, the official Python style guide.Python keywords: FalseNoneTrueandasbreakclassdefelifelseforifimportinisnotorreturnwhilewith
"123" in quotes is text, not a number. True has a capital T and no quotes.1name = input("What is your name? ")2city = input("Which city do you live in? ")3print("Hello", name + "!")4print("Welcome from", city)
input() does that job.1price = input("Price of one pen: ")2qty = input("How many pens? ")3total = price * qty4print("Total:", total)
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.
price = int(input("Price: ")). Next slide shows how.1price = int(input("Price of one pen: "))2qty = int(input("How many pens? "))3total = price * qty4print("Total: Rs", total)56height = float(input("Your height in metres: "))7print("Height in cm:", height * 100)89message = "You owe Rs " + str(total)10print(message)
| Function | Converts to | Example | Result |
|---|---|---|---|
int() | whole number | int("25") | 25 |
float() | decimal | float("1.62") | 1.62 |
str() | text | str(30) | '30' |
int() | drops decimals | int(9.99) | 9 |
int("abc") or int("12.5") crashes with a ValueError. In Module 13 you will learn to catch such errors.type() any time you are unsure what a variable holds.Python can fill several variables in one line. This is used everywhere, for example to swap two values or read x, y coordinates.
1a, b = 5, 10 # two variables in one line2print("Before:", a, b)34a, b = b, a # swap!5print("After:", a, b)67x = y = z = 0 # same value to many8score_ranchi, score_dhanbad = 245, 1989print(score_ranchi, score_dhanbad)
name = "Your Name" with name = input("Name? ")int(input(...)) and print the age in 10 yearsage * 365: your approximate age in daysname, class_sec, roll_no, city, is_memberroll_no on the last line1name = "Ankit Oraon"2class_sec = "9 A"3roll_no = 214city = "Ranchi"5is_member = True67print("=" * 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))
input()int()1name = input("Your name: ")2birth_year = int(input("Year you were born: "))34age_now = 2026 - birth_year5age_2030 = 2030 - birth_year67print("Hi", name + "!")8print("In 2026 you turn", age_now)9print("In 2030 you will be", age_2030)
usd_ratefloat(input())round(x, 2)1usd_rate = 84.0 # example rate: Rs 84 = 1 US dollar23rupees = float(input("Amount in rupees: "))4dollars = round(rupees / usd_rate, 2)5print("Rs", rupees, "=", "$", dollars)67back = round(dollars * usd_rate, 2)8print("Check:", dollars, "USD =", back, "rupees")
str() joining text and numbers1tea_price = 122samosa_price = 1534teas = int(input("Cups of tea: "))5samosas = int(input("Samosas: "))67tea_total = teas * tea_price8samosa_total = samosas * samosa_price9grand = tea_total + samosa_total1011print("-" * 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))
float)1km = float(input("Ride distance (km): "))2hours = float(input("Time taken (hours): "))34metres = km * 10005centimetres = km * 1000006miles = round(km * 0.621371, 2)7speed = round(km / hours, 1)89print("Distance:", km, "km")10print(" =", metres, "m")11print(" =", centimetres, "cm")12print(" =", miles, "miles")13print("Average speed:", speed, "km/h")
name = value stores the valuetype()input() always returns a stringint(), float(), str() before doing mathsa, b = b, a swaps two valuesWhat is type("45")?
Which is a valid variable name?
age = input("Age? ") and the user types 14. What is age?
* and +** (power)// and %username_ok and password_ok1a = 172b = 53print("a + b =", a + b) # addition4print("a - b =", a - b) # subtraction5print("a * b =", a * b) # multiplication6print("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
| Op | Name | Example | Result |
|---|---|---|---|
+ | add | 450 + 50 | 500 |
- | subtract | 500 - 120 | 380 |
* | multiply | 12 * 4 | 48 |
/ | divide | 10 / 4 | 2.5 |
// | floor divide | 10 // 4 | 2 |
% | remainder | 10 % 4 | 2 |
** | power | 2 ** 3 | 8 |
/ always gives a float: 10 / 2 is 5.0, not 5.17 chocolates, 5 friends. How many does each get, and how many are left?
| Use of % | Example |
|---|---|
| Even or odd? | n % 2 == 0 means even |
| Every 3rd item | i % 3 == 0 |
| Minutes left over | 200 % 60 = 20 |
10 + 2 * (6 - 3) ** 2 / 3| Priority | Operators |
|---|---|
| 1 (highest) | ( ) brackets |
| 2 | ** power |
| 3 | * / // % |
| 4 | + - |
| 5 | == != < > <= >= |
| 6 | not, then and, then or |
(price + tax) * qty is clearer and safer than relying on rules.Updating a variable using its own value is so common that Python gives shortcuts. Used for counters, scores and running totals.
1wallet = 5002print("Pocket money:", wallet)3wallet += 200 # same as wallet = wallet + 2004wallet -= 150 # bought a book5wallet *= 2 # Diwali bonus doubles it!6wallet //= 3 # shared with 2 siblings7print("Final:", wallet)
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | equal to | 5 == 5 | True |
!= | not equal | 5 != 3 | True |
> | greater than | 40 > 33 | True |
< | less than | 20 < 33 | True |
>= | greater or equal | 33 >= 33 | True |
<= | less or equal | 34 <= 33 | False |
= stores a value. == asks a question: "are these equal?" Mixing them up is the most common beginner bug.has_admit_card and on_time.age < 5 or age > 60.not is_blocked is True when the user is not blocked.| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | True | True | False |
| True | False | False | True | False |
| False | True | False | True | True |
| False | False | False | False | True |
1price = 399.4562print(round(price)) # nearest whole number3print(round(price, 2)) # 2 decimal places45temp_change = -76print(abs(temp_change)) # distance from 078print(max(45, 78, 62)) # biggest9print(min(45, 78, 62)) # smallest10print(pow(2, 10)) # same as 2 ** 1011print(10 ** 0.5) # square root of 10
round(total, 2).x ** 0.5 is the square root. In Module 11 you will also see math.sqrt().discount_percent 0 and check the totalint(input())total > 5000 to see if free delivery applies1price = float(input("Item price (Rs): "))2gst_rate = 1834gst = price * gst_rate / 1005total = price + gst67print("Price : Rs", round(price, 2))8print("GST @ 18% : Rs", round(gst, 2))9print("Total : Rs", round(total, 2))
/ for exact share, // for whole rupees% to find the rupees left over1bill = int(input("Bill amount: "))2friends = int(input("Number of friends: "))34tip = bill * 10 // 1005total = bill + tip6exact_share = total / friends7whole_share = total // friends8left_over = total % friends910print("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)")
1total = int(input("Video length in seconds: "))23hours = total // 36004minutes = (total % 3600) // 605seconds = total % 6067print(total, "seconds =", hours, "h", minutes, "min", seconds, "s")
and and print the result1theory = int(input("Theory marks (out of 80): "))2practical = int(input("Practical marks (out of 20): "))34total = theory + practical5percentage = total / 100 * 1006theory_ok = theory >= 80 * 30 / 1007overall_ok = percentage >= 338passed = theory_ok and overall_ok910print("Percentage :", percentage)11print("Theory OK :", theory_ok)12print("Overall OK :", overall_ok)13print("PASSED :", passed)
1P = float(input("Loan amount: "))2R = float(input("Interest rate per year (%): "))3T = int(input("Years: "))45simple_interest = P * R * T / 1006print("Simple interest :", round(simple_interest, 2))78r = R / 12 / 1009n = T * 1210emi = 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))
+ - * / // % **; / always gives a float// gives the whole part, % gives the remainder**, then * / // %, then + -x += 5 means x = x + 5== != > < >= <= give True or Falseand (both), or (any), not (flip)What is 17 % 5?
What is 2 + 3 * 2?
True and False gives?
strip() and check emails with "@" in emaillower() so "RANCHI" matches "ranchi"1city = "Ranchi"2state = 'Jharkhand'3quote = "It's the City of Waterfalls"4address = """BrainBit Infotech Pvt Ltd5Main Road, Ranchi6Jharkhand - 834001"""78print(city, state)9print(quote)10print(address)11print(len(city)) # number of characters12print(city + ", " + state) # join with +13print("-" * 20) # repeat with *
"It's".len("Ranchi") is 6."5" + "5" is "55", not 10. With strings, + joins.-1."D" + city[1:].Change the numbers or click a preset. Green boxes are picked.
| Slice | Meaning | Result |
|---|---|---|
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' |
"08-10-2026" with date[-4:], or the first name initial with name[0].| Method | What it does | Example 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 times | 2 |
.find(x) | position (or -1) | 3 |
.startswith(x) | True / False | True |
.isdigit() | only digits? | True |
name.upper() does not change name unless you store it: name = name.upper().1line = "Aman,Class 9,Ranchi,92"2parts = line.split(",")3print(parts)4print("Name:", parts[0])5print("Marks:", parts[3])67sentence = "Python is fun to learn"8words = sentence.split() # split on spaces9print(len(words), "words")1011print("-".join(["2026", "10", "08"]))12print(" | ".join(words))
sep between them."Aman,Class 9,Ranchi,92". split(",") is how programs read them. You will use this in Module 12.1name = "Priya"2marks = 4563total = 5004percent = marks / total * 10056print(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:,}")
| Inside { } | Result |
|---|---|
{percent:.2f} | 2 decimal places: 91.20 |
{125000:,} | thousands commas: 125,000 |
{8 + 1} | any expression: 9 |
"Hi " + name + ", you scored " + str(marks) vs f"Hi {name}, you scored {marks}". f-strings need no str()!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}")
| Format | Meaning |
|---|---|
:<12 | left-align in 12 spaces |
:>5 | right-align in 5 spaces |
:^27 | centre in 27 spaces |
:>10.2f | right-align, 2 decimals |
:*^27 | centre, fill with * |
1print("Line 1\nLine 2") # \n new line2print("Name:\tAman") # \t tab3print("She said \"Hello\"") # \" quote inside quotes4print("Path: C:\\python\\notes") # \\ one backslash5print(r"Raw: C:\new\test") # r"..." raw string67email = "priya@gmail.com"8print("@" in email)9print("yahoo" in email)10print("xyz" not in email)
| Code | Means |
|---|---|
\n | new line |
\t | tab |
\" \' | quote inside a string |
\\ | one backslash |
r"..." | raw: backslashes stay as they are |
Real sign-up forms receive messy text. Watch each method produce a new clean string.
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}")
:^301full_name = input("Full name: ")2year = input("Birth year: ")34first = full_name.strip().split()[0].lower()5username = first + year67print(f"Your username: {username}")8print(f"Length: {len(username)} characters")
1mobile = input("Mobile number: ")2masked = mobile[:2] + "X" * 6 + mobile[-2:]3print("Mobile:", masked)45email = input("Email: ")6at = email.find("@")7masked_email = email[:2] + "*" * (at - 2) + email[at:]8print("Email :", masked_email)
split()1text = """The Hundru Falls is one of the highest waterfalls in Jharkhand.2The Subarnarekha river falls from a height of about 98 metres."""34words = text.split()5no_spaces = text.replace(" ", "").replace("\n", "")67print("Words :", len(words))8print("Characters :", len(text))9print("Characters (no gaps):", len(no_spaces))10print("Times 'the' appears :", text.lower().split().count("the"))
:< and :>:,.2f1shop = "Gupta Stationers, Ranchi"2print(f"{shop:^40}")3print("=" * 40)4print(f"{'Item':<16}{'Qty':>5}{'Rate':>8}{'Amount':>11}")5print("-" * 40)67i1, q1, r1 = "Notebook", 12, 45.08i2, q2, r2 = "Gel pen (box)", 3, 120.09i3, q3, r3 = "Geometry box", 2, 1499.51011print(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*r316print(f"{'GRAND TOTAL':<29}{total:>11,.2f}")
strip().upper()pan[:5].isalpha(), pan[5:9].isdigit(), pan[9].isalpha()and and print the result1pan = input("Enter PAN: ").strip().upper()23length_ok = len(pan) == 104letters_ok = pan[:5].isalpha()5digits_ok = pan[5:9].isdigit()6last_ok = pan[9:].isalpha()78print(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}")
len() counts characters; + joins, * repeats-1 = last)s[start:stop:step]; stop is not included; s[::-1] reversesf"Hi {name}"; format with :.2f, :,, :<10\n new line, \t tab; "x" in s checks for text"PYTHON"[1:4] is?
" hi ".strip() gives?
f"{3.14159:.2f}" gives?
1marks = 722if marks >= 33:3 print("Pass") # indented = inside the if4 print("Well done!")5print("Result checked") # not indented = always runs
1age = int(input("Enter your age: "))23if age >= 18:4 print("You can vote in the Jharkhand elections.")5 print("Bring your Voter ID card.")6else:7 years = 18 - age8 print(f"Sorry, you can vote after {years} year(s).")910print("Thank you for using the Voter Help app.")
: or wrong indentation gives SyntaxError or IndentationError.1marks = int(input("Marks: "))23if 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"1314print("Grade:", grade)
Notice how Python skips the lines it does not need. Only one branch of the ladder runs.
1marks = 812if 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!")
1username = input("Username: ")2password = input("Password: ")34if 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.")
1if username == "admin" and password == "Ranchi@2026":2 print("Login successful")3else:4 print("Invalid username or password")
| Falsy (act like False) | Truthy (act like True) |
|---|---|
0, 0.0 | any other number |
"" empty string | "hello" |
[] empty list | [1, 2] |
None, False | True |
1name = input("Name: ")2if not name:3 print("Name cannot be empty!")
if not name: is the Pythonic way to check for an empty input in forms.1marks = 472result = "Pass" if marks >= 33 else "Fail"3print(result)45cart_total = 8506delivery = 0 if cart_total >= 499 else 407print(f"Delivery charge: Rs {delivery}")89n = 710print(f"{n} is", "even" if n % 2 == 0 else "odd")
1print("1. Litti Chokha 2. Dhuska 3. Pitha 4. Rugra curry")2choice = input("Your choice: ")34match 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")
| means OR: either value matches.else.python --version.if marks = 33:if marks >= 33if x > 5:
print("big")if city == "ranchi": (user typed Ranchi)if a == 1 or 2:if marks == 33:if marks >= 33:if x > 5:
print("big")if city.lower() == "ranchi":if a == 1 or a == 2:.lower()a == 1 or 2 is always True!1obtained = int(input("Marks obtained: "))2total = int(input("Total marks: "))3percent = obtained / total * 10045if 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"1718if grade == "A+":19 remark = "Excellent"20elif grade == "F":21 remark = "Needs improvement"22else:23 remark = "Good"2425print(f"Percentage : {percent:.2f}%")26print(f"Grade : {grade}")27print(f"Remark : {remark}")
1units = int(input("Units consumed: "))23if units <= 100:4 energy = units * 6.305elif units <= 200:6 energy = 100 * 6.30 + (units - 100) * 6.707else:8 energy = 100 * 6.30 + 100 * 6.70 + (units - 200) * 7.40910fixed = 7511total = energy + fixed12print(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}")
strip().lower()and1CORRECT_USER = "teacher01"2CORRECT_PASS = "Dav#Ranchi9"34user = input("Username: ").strip().lower()5pwd = input("Password: ")67if 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.")
1age = int(input("Passenger age: "))2km = int(input("Distance (km): "))3hour = int(input("Departure hour (0-23): "))45fare = km * 26if age < 5:7 fare = 08 category = "Infant (free)"9elif age <= 12:10 fare = fare / 211 category = "Child (half)"12elif age >= 60:13 fare = fare * 0.7514 category = "Senior (25% off)"15else:16 category = "Adult"1718night = 50 if hour >= 21 and fare > 0 else 019total = fare + night20print(f"Category : {category}")21print(f"Fare : Rs {fare:.2f}")22print(f"Night : Rs {night}")23print(f"TOTAL : Rs {total:.2f}")
case _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: "))56match choice:7 case "1":8 item, price = "Veg Thali", 1209 case "2":10 item, price = "Paneer Roll", 9011 case "3":12 item, price = "Chowmein", 8013 case "4":14 item, price = "Lassi", 5015 case _:16 item, price = None, 01718if item is None:19 print("Invalid order number!")20else:21 bill = price * qty22 if bill > 300:23 bill = bill * 0.924 print("10% discount applied")25 print(f"{qty} x {item} = Rs {bill:.2f}")
if condition: runs the indented block only when the condition is Trueelse: runs when it is False; elif checks more conditions in order: is required18 <= age <= 60x if cond else y; menus: match / caseif x = 5: is wrong because...
marks = 80. Which runs? if marks>=60: A elif marks>=75: B
bool("") is?
1print("Without a loop:")2print("Welcome, student 1")3print("Welcome, student 2")4print("Welcome, student 3")56print("With a loop:")7for n in range(1, 6):8 print("Welcome, student", n)
range(1, 101) and done.range(1, 11) gives 1 to 10.| Code | Numbers | Use for |
|---|---|---|
range(5) | 0 1 2 3 4 | repeat 5 times |
range(1, 6) | 1 2 3 4 5 | counting from 1 |
range(2, 21, 2) | 2 4 6 ... 20 | even numbers |
range(10, 0, -1) | 10 9 ... 1 | countdown |
range(0, 101, 25) | 0 25 50 75 100 | progress steps |
Watch how month takes the values 1, 2, 3, 4 and how total grows. This "running total" pattern is everywhere.
1total = 02for month in range(1, 5):3 saved = month * 1004 total = total + saved5 print(f"Month {month}: saved {saved}, total {total}")6print("Final total:", total)
1for letter in "RANCHI":2 print(letter, end=" ")3print()45cities = ["Ranchi", "Dhanbad", "Bokaro", "Jamshedpur"]6for city in cities:7 print("Sending parcel to", city)89for i, city in enumerate(cities, start=1):10 print(i, city)
[ ].1countdown = 52while countdown > 0:3 print(countdown, "...")4 countdown -= 15print("Lift off! Chandrayaan launched!")67balance = 10008months = 09while balance < 2000:10 balance = balance * 1.10 # 10% growth11 months += 112print(f"Doubled after {months} months: Rs {balance:.2f}")
| Use | When |
|---|---|
for | you know how many times or have a collection |
while | you repeat until something happens (unknown count) |
countdown -= 1 makes an infinite loop: the condition never becomes False. Press Ctrl+C to stop a stuck program.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 roll6 if roll == 7:7 print("Found topper at roll", roll, "- stop searching")8 break # leave the loop completely9 print("Checked roll", roll)10print("Search finished")
break: once the item is found, there is no need to check the rest.1balance = 50002while 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 -= amount11 print("Please collect Rs", amount)12 else:13 print("Insufficient balance")14 elif choice == "3":15 print("Thank you for banking with us!")16 break17 else:18 print("Invalid choice")
while True repeats forever...break runs1for row in range(1, 5):2 for col in range(1, row + 1):3 print("*", end=" ")4 print()56print()7for table in range(2, 4):8 for i in range(1, 4):9 print(f"{table} x {i} = {table * i}", end=" ")10 print()
The inner loop runs completely for each round of the outer loop. Row 1 prints 1 star, row 2 prints 2 stars...
| row | inner loop | prints |
|---|---|---|
| 1 | col = 1 | * |
| 2 | col = 1, 2 | * * |
| 3 | col = 1, 2, 3 | * * * |
| 4 | col = 1..4 | * * * * |
The inner loop finishes all its rounds (A, B) before the outer loop moves to the next row.
1for row in range(1, 4):2 for seat in "AB":3 print(f"{row}{seat}", end=" ")4 print()5print("All seats printed")
n to 8 and runrange(10, 0, -1)for i in range(1, 11)1n = int(input("Which table? "))2total = 03print(f"--- Table of {n} ---")4for i in range(1, 11):5 result = n * i6 total += result7 print(f"{n:>3} x {i:>2} = {result:>4}")8print(f"Sum of all results: {total}")
random.randint(1, 50) for the secret (import random at the top)while until the guess is right1import random2secret = random.randint(1, 50)3attempts = 04guess = 05print("I am thinking of a number from 1 to 50...")67while guess != secret:8 guess = int(input("Your guess: "))9 attempts += 110 if guess > secret:11 print("Too high!")12 elif guess < secret:13 print("Too low!")1415print(f"Correct! It was {secret}. You took {attempts} attempts.")
break and the loop else.for attempt in range(1, 4)break when the PIN is correctelse: on the for loop to block the card when all 3 attempts fail1CORRECT_PIN = "4826"23for 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 break8 else:9 left = 3 - attempt10 print(f"Wrong PIN. {left} attempt(s) left.")11else:12 print("Card blocked! Please contact your bank branch.")
" " * (h - i) then starsrange(h - 1, 0, -1) to go back down1h = int(input("Height: "))23print("Pyramid")4for i in range(1, h + 1):5 print(" " * (h - i) + "*" * (2 * i - 1))67print("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))
1goal = 150002savings = 03deposit = 10004month = 05print(f"{'Month':>5} {'Deposit':>8} {'Savings':>10}")6while savings < goal:7 month += 18 savings = savings * 1.005 + deposit9 print(f"{month:>5} {deposit:>8} {savings:>10,.2f}")10 deposit += 20011print(f"Goal reached in {month} months!")
for x in range(a, b, step): stop b is not includedfor works on strings, lists, ranges; enumerate() adds numberingwhile condition: repeats until the condition is False; update the variable!break exits, continue skips to the next round, loop else runs if no breakHow many times does for i in range(2, 8): run?
Which keyword skips to the next round?
while x > 0: with no change to x causes...
You finished Python Foundations: 6 modules and 30 practice examples.
D:\python-practice\part1