Chapter 4: Programming in Python
Stop reading about code and start writing it. Variables, decisions, loops, lists, functions, files and charts: every example here is short, tested and copy-paste ready.
python.org, or use a free online editor like programiz.com/python-programming/online-compiler or replit.com. Click ๐ Copy on any code box, paste it, press Run. Reading code teaches you 20%. Running and breaking it teaches you the other 80%.
1 Introduction to Python
A computer is very fast but very obedient: it only does exactly what it is told. A programming language is how we tell it. Out of hundreds of languages, Python is the one most beginners start with, because Python code reads almost like plain English.
Compare how two languages say the same thing:
| Language | Code to print "Hello" |
|---|---|
| Java | public class A { public static void main(String[] a){ System.out.println("Hello"); } } |
| Python | print("Hello") |
Why Python is worth your time
Easy to read
Short, English-like syntax. Less typing, fewer mistakes.
Free & open-source
Download and use it without paying anything.
Huge libraries
Ready-made code for AI, charts, games and websites.
Runs everywhere
Windows, macOS, Linux, even a Raspberry Pi.
Real jobs
Used by Google, YouTube, Instagram, NASA and Nepali IT companies.
Here is your very first program. Two lines, and the computer talks back:
print("Hello, Nepal!")
print("Welcome to Python programming.")
print() shows output on the screen. Whatever is inside the quotes is printed exactly as it is, even spelling mistakes.
2 Python Variables
Think of your school bag. Each pocket has a name ("water bottle pocket", "tiffin pocket") and holds something. A variable is exactly that: a named pocket in the computer's memory.
In Python you create a variable just by giving it a name and a value with =. You do not write the data type; Python figures it out on its own.
name = "Sita" # text -> str
age = 16 # whole number -> int
height = 5.4 # decimal -> float
is_student = True # True / False -> bool
print(name, age, height, is_student)
print(type(age)) # ask Python what type it is
The word variable means "can vary". The same pocket can hold a new value later, and the old one is simply replaced:
balance = 500 # eSewa balance
print("Before:", balance)
balance = balance - 120 # bought a recharge card
print("After:", balance)
# is a comment. Python ignores it completely; it is a note for humans (including future-you) reading the code.
= means "put this value in the box". == means "are these two equal?". Mixing them up is the number-one beginner error.
3 Rules for Python Variables
You can name a variable almost anything, but five rules must be followed or Python refuses to run the program:
- Use only letters, numbers and underscore (_).
- It must start with a letter or an underscore, never with a number.
- No spaces are allowed. Use
_instead. - Names are case-sensitive:
age,AgeandAGEare three different variables. - You cannot use Python keywords such as
if,for,while,class,True.
| โ Valid | โ Invalid | Reason it fails |
|---|---|---|
my_age | my age | Space is not allowed |
total1 | 1total | Cannot start with a number |
_name | na@me | Special symbol not allowed |
roll_no | for | Reserved keyword |
total_marks | total-marks | - is read as minus |
x = 85 tells you nothing next week; math_marks = 85 tells you everything. Professionals write code for humans to read.
4 Input and Output in Python
A program that always prints the same thing is boring. Real programs ask the user something and answer back, exactly like an ATM asking for your amount.
print() sends output to the screen. input() takes input from the keyboard and always returns it as text (string).
That last word matters. Because input() gives text, you must convert it with int() or float() before doing any maths:
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # text -> number
print("Namaste,", name)
print("Next year you will be", age + 1)
A real one: the momo shop bill.
plates = int(input("How many plates of momo? "))
rate = 180
total = plates * rate
print("Total bill: Rs.", total)
int() and age + 1 crashes with TypeError. Worse, plates * rate would silently print the text three times instead of multiplying. Always convert before calculating.
5 String Formatting
Printing values with commas works, but the sentence looks untidy. String formatting lets you drop variables neatly inside a sentence, the way an SMS from your bank does: "Dear Sita, Rs. 500 credited."
The easiest modern way is the f-string: put the letter f before the quotes and wrap variables in { }.
name = "Sita"
marks = 92
# 1. f-string (recommended)
print(f"{name} scored {marks} marks.")
# 2. .format() method
print("{} scored {} marks.".format(name, marks))
# 3. maths works inside the braces too
print(f"Out of 100, {name} lost {100 - marks} marks.")
You can also control decimal places, which is exactly what you need for money and percentages:
total = 247
percent = total / 3
print(f"Percentage: {percent}") # ugly
print(f"Percentage: {percent:.2f}%") # 2 decimal places
f. print("{name} scored") prints the braces literally instead of the value.
6 Operators in Python
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division (always decimal) | 5 / 2 | 2.5 |
// | Floor division (drops decimal) | 5 // 2 | 2 |
% | Modulus (remainder) | 5 % 2 | 1 |
** | Power | 5 ** 2 | 25 |
// and % are actually used: You have Rs. 500 and one momo plate costs Rs. 180. 500 // 180 = 2 plates you can buy, and 500 % 180 = Rs. 140 left in your pocket. That is the whole point of those two operators.
Relational (Comparison) Operators
These compare two values and always answer True or False.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 40 == 40 | True |
!= | Not equal to | 40 != 32 | True |
> | Greater than | 90 > 40 | True |
< | Less than | 90 < 40 | False |
>= | Greater than or equal | 40 >= 40 | True |
<= | Less than or equal | 39 <= 40 | True |
Logical Operators
and needs both sides true. or needs at least one side true. not flips the answer.
english = 72
math = 35
print(english >= 40 and math >= 40) # passed BOTH subjects?
print(english >= 40 or math >= 40) # passed AT LEAST one?
print(not (math >= 40)) # failed math?
Assignment and Membership Operators
score = 10
score += 5 # same as: score = score + 5
score -= 3 # same as: score = score - 3
print(score)
subjects = ["Nepali", "English", "Math"]
print("Math" in subjects) # membership
print("Science" not in subjects)
/, // and % is asked almost every year. 7 / 2 = 3.5, 7 // 2 = 3, 7 % 2 = 1.
7 Conditional Statements (if, elif, else)
Every morning you make a decision: "If it is raining, take the umbrella, otherwise don't." A conditional statement is how a program makes that same kind of choice.
True. Python uses if, elif (else-if) and else.
marks = int(input("Enter your marks: "))
if marks >= 90:
print("Grade A+")
elif marks >= 60:
print("Grade A")
elif marks >= 40:
print("Pass")
else:
print("Fail")
Python checks the conditions from top to bottom and stops at the first True one. That is why we write the highest grade first. Write them in the wrong order and every student becomes a "Pass".
Indentation: Python's one strict rule
Other languages use { } to group lines. Python uses spaces. Lines that belong inside an if must be pushed in by the same amount, normally 4 spaces.
age = 18
if age >= 18:
print("You can vote.") # inside the if (4 spaces)
print("Bring your ID.") # also inside
print("Program finished.") # outside, runs always
: at the end of the if line, and mixing tabs with spaces. Pick 4 spaces and stay consistent.
%. Then extend it: also say "Zero" if the number is 0.
8 Iteration / Loops in Python
Imagine writing the 7 times table by hand: 12 nearly identical lines. Now imagine the table up to 1000. A loop writes it once and lets the computer repeat it.
For Loop
Use it when you know how many times to repeat. range(1, 6) gives 1, 2, 3, 4, 5: it includes the start and stops before the end.
# The 7 times table
for i in range(1, 6):
print(f"7 x {i} = {7 * i}")
A for loop can also walk through a list, one item at a time:
students = ["Sita", "Ram", "Gita"]
for student in students:
print("Present:", student)
While Loop
Use it when you do not know the count, only the stopping condition: like a shopkeeper who keeps serving until the queue is empty.
balance = 500
while balance >= 180:
balance = balance - 180
print("Bought 1 plate of momo. Left: Rs.", balance)
print("Not enough money now. Rs.", balance)
break and continue
for i in range(1, 11):
if i == 4:
continue # skip just this one
if i > 6:
break # stop the loop completely
print(i, end=" ")
| Point | for loop | while loop |
|---|---|---|
| Use when | Number of repeats is known | Only the stop condition is known |
| Counter | Handled automatically by range() | You must change it yourself |
| Typical use | Tables, lists, fixed counts | Menus, games, "keep asking until correct" |
while loop, if you forget to change the variable (e.g. count = count + 1), the condition never becomes false and the program runs forever. This is an infinite loop. Press Ctrl + C to stop it.
range(2, 21, 2) counts in steps of 2.
9 Data Structures in Python
One variable holds one value. But a class has 40 students, a shop has 200 items. Making student1, student2 ... student40 would be madness. A data structure holds many values under one name.
| Structure | Symbol | Key point | Example |
|---|---|---|---|
| List | [ ] | Ordered, changeable, allows duplicates | [10, 20, 30] |
| Tuple | ( ) | Ordered, cannot be changed | (10, 20) |
| Dictionary | { } | Stores key : value pairs | {"name": "Ram"} |
| Set | { } | Unordered, no duplicates allowed | {1, 2, 3} |
marks = [55, 90, 70] # list - can change
birth = (2065, 7, 12) # tuple - fixed forever
student = {"name": "Ram", "age": 15} # dictionary
rolls = {5, 8, 5, 12} # set - duplicate 5 removed
print(marks, birth, student, rolls)
10 List
A list is like the attendance register: names written in a fixed order, each with a position number. In Python that position is called the index, and it starts from 0, not 1.
[ ], separated by commas. It is ordered and changeable.
| Item | "apple" | "banana" | "orange" |
|---|---|---|---|
| Index (forward) | 0 | 1 | 2 |
| Index (backward) | -3 | -2 | -1 |
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # first item
print(fruits[-1]) # last item (counting backwards)
print(fruits[0:2]) # slice: index 0 and 1, NOT 2
fruits[1] = "mango" # change an item
print(fruits)
fruits[0] and the last is fruits[-1]. Asking for fruits[3] in a 3-item list gives IndexError: list index out of range, because index 3 would be the fourth item.
11 Built-in List Functions
Python already knows how to count, add up and sort a list. You do not have to write any of it yourself.
| Function | What it does | Example on [55, 90, 70] |
|---|---|---|
len(list) | Counts the items | 3 |
sum(list) | Adds all numbers | 215 |
max(list) | Largest value | 90 |
min(list) | Smallest value | 55 |
list.append(x) | Adds x at the end | [55, 90, 70, x] |
list.insert(i, x) | Inserts x at position i | โ |
list.remove(x) | Removes the first x found | โ |
list.sort() | Arranges in order | [55, 70, 90] |
Put together, these four lines are a complete result summary:
marks = [55, 90, 70, 40]
print("Subjects :", len(marks))
print("Total :", sum(marks))
print("Highest :", max(marks))
print("Lowest :", min(marks))
print("Average :", sum(marks) / len(marks))
marks.append(100) # a new subject result arrived
marks.sort() # arrange smallest to largest
print(marks)
sum(list) / len(list) is the average. That single line answers a very common "write a program to find the average marks" question.
12 Dictionary in Python
In a list you must remember that position 2 holds the age. In your phone's contact list you do not remember positions: you search "Aama" and get the number. A dictionary works the same way.
{ }. The value is found using its key instead of a number index.
student = {
"name": "Sita",
"age": 16,
"class": 10
}
print(student["name"]) # read a value using its key
student["age"] = 17 # change a value
student["city"] = "Pokhara" # add a brand-new pair
print(student)
A phonebook is the most natural example of all:
phonebook = {
"Aama": "9841000001",
"Buwa": "9841000002",
"School": "014400000"
}
who = "Buwa"
print(f"{who}'s number is {phonebook[who]}")
phonebook["Didi"]) causes a KeyError and the program stops. Use .get() instead: it returns None quietly. See the next topic.
| Point | List | Dictionary |
|---|---|---|
| Written with | [ ] | { } |
| Accessed by | Number index (0, 1, 2 ...) | Key (a name you choose) |
| Best for | A simple sequence of values | Values that need labels |
| Example | [80, 95] | {"Ram": 80, "Sita": 95} |
13 Built-in Dictionary Functions
| Function | What it does |
|---|---|
dict.get(key) | Returns the value; gives None instead of crashing if the key is missing |
dict.keys() | Returns all the keys |
dict.values() | Returns all the values |
dict.items() | Returns each key and value together as a pair |
len(dict) | Counts the pairs |
del dict[key] | Removes one key : value pair |
student = {"name": "Ram", "age": 15, "class": 10}
print(student.get("name"))
print(student.get("address")) # missing key -> None, no crash
print(student.keys())
print(student.values())
print("Pairs:", len(student))
del student["age"]
print(student)
Looping through a dictionary with .items() is how you print a whole marksheet in three lines:
marksheet = {"Nepali": 78, "English": 65, "Math": 92}
for subject, mark in marksheet.items():
print(f"{subject:10} : {mark}")
print("Total:", sum(marksheet.values()))
14 String Manipulation
Text is everywhere in real programs: names, addresses, passwords, search boxes. Python gives ready-made tools to clean and change text.
| Function | Use | Example โ Result |
|---|---|---|
upper() | Make UPPERCASE | "ram".upper() โ RAM |
lower() | Make lowercase | "RAM".lower() โ ram |
title() | Capitalise Each Word | "ram thapa".title() โ Ram Thapa |
strip() | Remove extra spaces at both ends | " ram ".strip() โ ram |
replace() | Swap one part for another | "2080".replace("0", "1") โ 2181 |
split() | Break text into a list | "a,b".split(",") โ ['a', 'b'] |
len() | Count the characters | len("Nepal") โ 5 |
count() | Count one letter | "banana".count("a") โ 3 |
text = "Technology Channel"
print(text.upper())
print(text.lower())
print("Length:", len(text))
print("Number of 'n':", text.count("n"))
print(text.replace("Channel", "Nepal"))
print(text.split(" "))
A tiny real use: making a clean username from a messy typed name.
full_name = " Sita Sharma "
clean = full_name.strip().lower().replace(" ", "_")
print("Username:", clean)
Useful number functions too
print(abs(-7)) # absolute (always positive)
print(pow(2, 5)) # 2 to the power 5
print(round(3.678, 2))# round to 2 decimals
print(hex(255)) # decimal to hexadecimal
text.upper() only helps if you print it or store it: text = text.upper().
15 Library Function vs User-Defined Function
You have already used functions: print(), len() and input() are all functions written by the Python team. Functions you write yourself are called user-defined.
| Point | Library (Built-in) Function | User-Defined Function |
|---|---|---|
| Who wrote it | The Python developers | You, the programmer |
| How to use | Just call it | First define it with def, then call it |
| Purpose | Common, general jobs | Your program's own special job |
| Examples | print(), len(), sum(), max() | def calculate_grade(marks): |
marks = [80, 95, 60]
print(sum(marks)) # LIBRARY function
def total_with_bonus(m): # USER-DEFINED function
return sum(m) + 5
print(total_with_bonus(marks))
def.
16 Advantages of Functions
Suppose your program calculates a grade in six different places. Without a function you copy those eight lines six times. Then the grading rule changes... and you must fix it six times, and you will miss one.
Reusable
Write it once, call it a hundred times.
Less code
Removes repeated lines, so the file stays short.
Organised
Breaks one big problem into small solvable parts.
Easy to fix
Change the rule in one place and everywhere updates.
Readable
calculate_grade(85) explains itself.
Teamwork
Different people can write different functions.
17 Creating a Function
A function is created with the def keyword. Every function has four parts, and the exam often asks you to name them:
def+ name: defines and names the function.- Parameter list: the inputs, written inside
( ). return: sends a result back (optional).- Function call: the line that actually runs it.
def add(a, b): # 1 & 2: def + name + parameters
result = a + b
return result # 3: return the answer
answer = add(5, 3) # 4: function call
print("Sum is", answer)
Something more useful. This one function now decides every grade in your whole program:
def grade(marks):
if marks >= 90:
return "A+"
elif marks >= 60:
return "A"
elif marks >= 40:
return "Pass"
else:
return "Fail"
print("Sita:", grade(92))
print("Ram :", grade(35))
print("Gita:", grade(74))
def only teaches Python the recipe; nothing cooks until you write grade(92).
18 Parameters and Arguments
Think of a tea shop. The menu says "one cup of tea with sugar level" โ sugar level is the parameter. When you order "two spoons", two spoons is the argument.
def greet(name): # 'name' is the PARAMETER
print("Namaste,", name)
greet("Sita") # "Sita" is the ARGUMENT
greet("Ram")
| Parameter | Argument |
|---|---|
| Written in the function definition | Written in the function call |
| Just a placeholder name | A real value |
def greet(name): | greet("Sita") |
TypeError.
19 Scope of Variables (Local & Global)
- Local variable: created inside a function. It exists only while that function runs and cannot be used outside.
- Global variable: created outside all functions. It can be read anywhere in the program.
A useful picture: the school notice board is global (everyone can read it), while a note in your own pocket is local (only you have it).
school = "Shree Janata School" # GLOBAL
def show():
msg = "Welcome" # LOCAL
print(msg, "to", school) # global can be read here
show()
print(school) # works
# print(msg) # ERROR: msg does not exist here
| Point | Local variable | Global variable |
|---|---|---|
| Created | Inside a function | Outside all functions |
| Usable | Only inside that function | Anywhere in the program |
| Lifetime | Destroyed when the function ends | Lives until the program ends |
NameError. If a function's result is needed outside, return it instead.
20 Return Values: One, None or Many
A function can hand something back to the line that called it. That is return. Some functions return one value, some return nothing, some return several at once.
1. Returning one value
def square(n):
return n * n
area = square(4) # the returned value is stored
print(area)
2. Returning nothing (None)
def greet():
print("Hello!") # it does a job, but returns nothing
x = greet()
print("Returned value:", x)
3. Returning many values
def calc(a, b):
return a + b, a - b, a * b # three values at once
total, diff, product = calc(10, 4)
print(total, diff, product)
print() inside a function only shows a value; it does not give it back. If you want to use the answer later in a calculation, you must return it.
21 Types of Function Arguments
There are three common ways to pass values into a function:
Positional
Matched by their order. The first value goes to the first parameter.
Default
The parameter already has a value, used when you do not pass one.
Keyword
Passed by name, so the order no longer matters.
def student(name, country="Nepal"): # country has a DEFAULT
print(name, "-", country)
student("Sita") # positional (default used)
student("Ram", "India") # positional (default replaced)
student(country="USA", name="Gita") # keyword, order changed
def f(a=1, b) is an error; def f(b, a=1) is correct.
22 Libraries in Python
Nobody grinds their own spices to cook dal bhat every day; you buy the masala ready-made. A library is ready-made code, so you never have to invent square roots or bar charts yourself.
| Point | Standard Library | External Library |
|---|---|---|
| Availability | Comes with Python automatically | Must be installed using pip |
| Cost of use | Just import it | Install once, then import |
| Examples | math, random, os, datetime, csv, turtle | numpy, pandas, matplotlib, scipy, scikit-learn |
NumPy
Very fast maths on large sets of numbers.
Pandas
Works with tables of data, like Excel in code.
Matplotlib
Draws charts and graphs from data.
SciPy
Advanced science and engineering maths.
Scikit-learn
Machine learning: teaching computers to predict.
23 Python Packages
.py file containing functions. A package is a folder that groups many related modules together. A library is a collection of packages and modules.
The easiest way to picture it: module = one page, package = one chapter, library = the whole book.
External packages are installed with pip, Python's package installer:
pip install numpy
pip install pandas matplotlib
pip install pandas inside a Python program gives a SyntaxError. pip commands belong in the terminal / command prompt, not in the code.
24 Importing and Using Libraries
Before using a library you must import it, normally at the very top of the file. There are three ways:
# 1. Import the whole module
import math
print(math.sqrt(25))
# 2. Import one specific function from it
from math import sqrt
print(sqrt(36))
# 3. Import with a short nickname (alias)
import math as m
print(m.pi)
| Way | How you call it | Best when |
|---|---|---|
import math | math.sqrt(25) | You need several functions from it |
from math import sqrt | sqrt(25) | You need only one or two |
import math as m | m.sqrt(25) | The name is long, e.g. pandas as pd |
sqrt(25) after writing only import math gives NameError. With that import style you must write the module name too: math.sqrt(25).
25 Popular Libraries (with examples)
math module: maths without the hard work
import math
print(math.sqrt(49)) # square root
print(math.pow(2, 4)) # power
print(math.factorial(5)) # 5! = 5x4x3x2x1
print(math.gcd(12, 18)) # greatest common divisor
print(math.ceil(4.1)) # round UP
print(math.floor(4.9)) # round DOWN
random module: dice, lotteries and quizzes
import random
print(random.randint(1, 6)) # roll a dice
print(random.choice(["Ram", "Sita", "Gita"])) # pick a name
names = ["Ram", "Sita", "Gita"]
random.shuffle(names) # mix the order
print(names)
random gives a different answer every run. Your output will not match the one above, and that is exactly right.
datetime module: today's date
import datetime
today = datetime.date.today()
print("Today is:", today)
print("Year:", today.year)
pandas: data in neat tables
import pandas as pd
data = {"Name": ["Ram", "Sita"], "Marks": [80, 95]}
df = pd.DataFrame(data)
print(df)
print("Average marks:", df["Marks"].mean())
random.randint(1, 6), add them, and print "You win!" if the total is 7.
26 Turtle Graphics
The turtle module gives you a small pen (the "turtle") that you order around the screen: forward, turn, forward, turn. It is the most enjoyable way to see what a loop actually does.
| Command | What the turtle does |
|---|---|
forward(100) | Moves 100 steps ahead, drawing a line |
right(90) / left(90) | Turns 90 degrees on the spot |
penup() / pendown() | Stops / starts drawing while moving |
color("red") | Changes the line colour |
circle(50) | Draws a circle of radius 50 |
import turtle
pen = turtle.Turtle()
# Draw a square: 4 sides, turning 90 degrees each time
for i in range(4):
pen.forward(100)
pen.right(90)
turtle.done()
The magic rule: the turtle must turn a total of 360 degrees to close any shape. So for a shape with n sides, the turn is 360 / n.
| Shape | Sides | Angle to turn |
|---|---|---|
| Triangle | range(3) | 120 |
| Square | range(4) | 90 |
| Pentagon | range(5) | 72 |
| Hexagon | range(6) | 60 |
| Circle-ish | range(360) | 1 |
range(5) and pen.right(144). Then wrap the whole square code in another loop that turns 10 degrees each time, and watch a flower appear.
27 Matplotlib & Data Visualisation
A column of 40 numbers tells you nothing. The same 40 numbers as a bar chart instantly show who is struggling. That is the entire reason charts exist.
Bar Chart: comparing categories
import matplotlib.pyplot as plt
subjects = ["Nepali", "Math", "Science"]
marks = [78, 92, 85]
plt.bar(subjects, marks)
plt.title("My Marks")
plt.xlabel("Subject")
plt.ylabel("Marks")
plt.show()
Line Chart: showing change over time
import matplotlib.pyplot as plt
months = ["Baisakh", "Jestha", "Asar", "Shrawan"]
sales = [1200, 1500, 900, 1800]
plt.plot(months, sales, marker="o")
plt.title("Shop Sales")
plt.ylabel("Rs.")
plt.show()
Pie Chart: showing parts of a whole
import matplotlib.pyplot as plt
labels = ["Study", "Sleep", "Play", "Other"]
hours = [8, 8, 3, 5]
plt.pie(hours, labels=labels, autopct="%1.0f%%")
plt.title("My Day in 24 Hours")
plt.show()
| Chart | Use it when you want to show |
|---|---|
| Bar chart | Comparison between separate categories |
| Line chart | A change or trend over time |
| Pie chart | Parts of one whole (percentages) |
| Scatter plot | Relationship between two quantities |
plt.show(). Also install it first with pip install matplotlib. Related tools: Seaborn for prettier statistical charts and Plotly for interactive ones.
plt.bar to plt.barh and see it turn sideways.
28 Errors and Exceptions
Every programmer in the world, from beginner to expert, sees errors daily. An error is not a failure; it is Python telling you precisely what it did not understand. Learn to read it and you have learned to debug.
| Error | Cause | Example |
|---|---|---|
SyntaxError | Wrong grammar | Missing : after if |
NameError | Using an undefined variable | print(mark) when you typed marks |
TypeError | Mixing incompatible types | "5" + 5 |
ValueError | Right type, wrong value | int("abc") |
ZeroDivisionError | Dividing by zero | 10 / 0 |
IndexError | Index outside the list | [1, 2][5] |
KeyError | Dictionary key not found | d["missing"] |
IndentationError | Wrong spacing | Line not lined up |
Handling exceptions with try and except
Imagine an ATM crashing because someone typed "abc" instead of an amount. try and except prevent exactly that.
try:
num = int(input("Enter a number: "))
print("100 divided by your number is", 100 / num)
except ZeroDivisionError:
print("Error: cannot divide by zero!")
except ValueError:
print("Error: please type a valid number!")
finally:
print("Thank you for using this program.")
| Block | When it runs |
|---|---|
try | Always: it holds the risky code |
except | Only if that particular error happens |
else | Only if no error happened |
finally | Always, error or not (used for clean-up) |
29 File Handling & Modes
Close your program and every variable disappears: memory is temporary. To keep data for tomorrow, write it to a file on the disk. That is how your school's result software still has last year's marks.
open("filename", "mode").
| Mode | Name | What it does | If the file is missing |
|---|---|---|---|
"r" | Read | Opens the file only to read it | Error |
"w" | Write | Writes, erasing everything already inside | Creates it |
"a" | Append | Adds to the end, keeping the old content | Creates it |
"x" | Create | Creates a brand-new file | Error if it already exists |
"w" deletes the existing content the moment the file is opened, before you write a single character. When you mean "add more", use "a".
"a" every evening to append today's list, and "r" at month-end to read the whole month back.
30 Write, Read, Update & Delete a File
1. Write to a file
f = open("notes.txt", "w")
f.write("Hello from Python!\n")
f.write("This is line two.")
f.close()
print("File saved.")
2. Read a file
f = open("notes.txt", "r")
content = f.read()
f.close()
print(content)
3. Update (append more)
f = open("notes.txt", "a")
f.write("\nA new line added later.")
f.close()
print(open("notes.txt").read())
4. Delete a file
import os
os.remove("notes.txt")
print("File deleted.")
The safer modern way: with
Forgetting f.close() can lose data. The with statement closes the file for you automatically, even if an error happens.
with open("diary.txt", "w") as f:
f.write("Aaja Python sikeko din.")
# file closes automatically here
with open("diary.txt", "r") as f:
for line in f:
print(line)
\n means "start a new line". Without it, everything you write gets stuck together on one long line.
31 CSV Read & Write
A CSV of student marks is literally just this text:
Name,Marks
Ram,80
Sita,95
Write a CSV
import csv
with open("students.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Marks"]) # header row
writer.writerow(["Ram", 80])
writer.writerow(["Sita", 95])
print("CSV written.")
Read a CSV
import csv
with open("students.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
'80' in quotes above. To add marks up you must convert: int(row[1]).
Reading it back and calculating properly:
import csv
total = 0
with open("students.csv", "r") as f:
reader = csv.reader(f)
next(reader) # skip the header row
for row in reader:
total = total + int(row[1])
print("Total marks:", total)
students.csv you created in Excel or Google Sheets. Same file, two completely different programs reading it: that is why CSV is everywhere.
32 Mini Project: Student Result System
Time to put everything together. This project uses input, list, dictionary, loop, function, if-else and CSV: nearly every topic in this chapter. Build it step by step and you have written real software.
Step 1: The grading function
def grade(percent):
if percent >= 90:
return "A+"
elif percent >= 80:
return "A"
elif percent >= 60:
return "B"
elif percent >= 40:
return "C"
else:
return "Fail"
print(grade(92), grade(64), grade(31))
Step 2: Collect the marks
students = []
for i in range(2):
name = input("Student name: ")
nepali = int(input("Nepali marks: "))
english = int(input("English marks: "))
math = int(input("Math marks: "))
total = nepali + english + math
percent = total / 3
students.append({
"name": name,
"total": total,
"percent": percent,
"grade": grade(percent)
})
Step 3: Print the result sheet
print("\n------ RESULT SHEET ------")
for s in students:
print(f"{s['name']:10} {s['total']:4} {s['percent']:6.2f}% {s['grade']}")
topper = max(students, key=lambda s: s["total"])
print("Topper:", topper["name"])
Step 4: Save it forever (CSV)
import csv
with open("result.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Total", "Percent", "Grade"])
for s in students:
writer.writerow([s["name"], s["total"], round(s["percent"], 2), s["grade"]])
print("Result saved to result.csv")
result.csv back and print only the students who passed.
๐ Exercises & Quiz
Test what you've learned! Click Show Answer to check yourself. Try honestly first: the answer only helps after you have attempted it.
๐ Short Terms / Glossary
๐ค Full Forms (Click "Reveal" to check)
โ Choose the Correct Answer (MCQ)
input() always return?7 // 2?for i in range(1, 5): repeat?int("abc") raises which error?๐ฎ Predict the Output (think first, then reveal)
a = 17
b = 5
print(a / b, a // b, a % b)
3.4 3 2 โ / always gives a decimal, // drops the decimal part, % gives the remainder.
marks = [40, 55, 90]
print(marks[1], marks[-1], len(marks))
55 90 3 โ index 1 is the second item because counting starts at 0, and -1 means the last item.
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ")
1 2 4 5 โ continue skips only that one turn of the loop; it does not stop the loop.
def add(a, b=10):
return a + b
print(add(5), add(5, 20))
15 25 โ the first call uses the default b = 10, the second replaces it with 20.
text = "Nepal"
print(text.upper())
print(text)
NEPAL then Nepal โ string methods return a new string; the original variable is unchanged unless you reassign it.
๐ Find the Bug (each program has exactly one mistake)
age = input("Enter age: ")
print("Next year:", age + 1)
input() returns text, so Python cannot add 1 to it (TypeError).Fix:
age = int(input("Enter age: "))
count = 1
while count <= 5:
print(count)
count is never increased, so the condition stays true forever (infinite loop).Fix: add
count = count + 1 inside the loop.
marks = 80
if marks >= 40
print("Pass")
if line.Fix:
if marks >= 40:
def total(a, b):
print(a + b)
result = total(4, 6)
print("Result is", result)
return it, so result becomes None.Fix: change
print(a + b) to return a + b.
f = open("diary.txt", "w")
f.write("New entry")
f.close()
"w" erases everything already in the file.Fix: use mode
"a" to append instead.
โ๏ธ Short Answer Questions
int() with input() when taking a number?input() always returns the typed value as a string. Arithmetic cannot be performed on a string, so int() (or float()) converts it into a number first. Without it, the program raises a TypeError.
/, // and % with an example./ gives normal division with a decimal (7 / 2 = 3.5), // gives floor division with the decimal removed (7 // 2 = 3), and % gives the remainder (7 % 2 = 1).
if, loop or function. Wrong indentation changes the meaning of the program or causes an IndentationError.
for loop is used when the number of repetitions is known in advance (it loops over a range or list). A while loop repeats as long as a condition remains true, and is used when the exact count is not known.
count = count + 1.
[ ] and each item is accessed by a number index. A dictionary stores key : value pairs inside { } and each value is accessed by its key.
[ ] and its items can be changed, added or removed. A tuple is written in ( ) and cannot be changed after it is created, which makes it safe for fixed data such as a date of birth.
print() or len(). A user-defined function is written by the programmer using the def keyword for a specific need.
.py file containing functions. A package is a folder that groups related modules together. A library is a collection of packages and modules that provides ready-made code.
"r" opens a file to read it; "w" writes, erasing any existing content; "a" appends new data to the end while keeping the old content; "x" creates a new file and raises an error if it already exists.
ZeroDivisionError. try holds the risky code and except handles the error, so the program shows a friendly message instead of crashing.
a = int(input("a: "))b = int(input("b: "))c = int(input("c: "))print("Largest is", max(a, b, c))
marks = [55, 90, 70, 40]print("Total:", sum(marks))print("Average:", sum(marks) / len(marks))
๐ ๏ธ Practical Ideas (Try in the lab)
- Calculator: take two numbers and print their +, โ, ร, รท results.
- Even or Odd: ask for a number and use
%to decide. - Multiplication table: use a for loop to print the table of any number.
- Pass or fail: take marks of three subjects and print the grade using a function.
- Marks list: store 5 marks in a list and print the total, highest, lowest and average.
- Phonebook: use a dictionary of name : number and look up a contact by name.
- Momo bill: ask how many plates and print the bill with 13% VAT added.
- Guess the number: use
random.randint(1, 10)and a while loop to let the user keep guessing. - Turtle art: draw a square, a triangle and a five-pointed star using loops.
- Bar chart: plot your subject marks using matplotlib.
- Save & read: write your name and class to a text file, then read it back.
- Attendance CSV: save five classmates' names and attendance to a CSV, then count how many were present.