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.

Before you start: Install Python from 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.

Python is a simple, easy-to-read, high-level, general-purpose programming language created by Guido van Rossum in 1991. It is used for web development, data science, artificial intelligence, automation and games.

Compare how two languages say the same thing:

LanguageCode to print "Hello"
Javapublic class A { public static void main(String[] a){ System.out.println("Hello"); } }
Pythonprint("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:

Python
print("Hello, Nepal!")
print("Welcome to Python programming.")
Hello, Nepal! Welcome to Python programming.
Remember: print() shows output on the screen. Whatever is inside the quotes is printed exactly as it is, even spelling mistakes.
๐ŸŽฎ Try it yourself: Change the message to your own name and school. Then remove one quotation mark and run it again: read the error message Python gives you. Learning to read errors is a real programming skill, and it starts today.

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.

A variable is a name that stores a value in the computer's memory, so the value can be used and changed later.

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.

Python
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
Sita 16 5.4 True <class 'int'>

The word variable means "can vary". The same pocket can hold a new value later, and the old one is simply replaced:

Python
balance = 500        # eSewa balance
print("Before:", balance)

balance = balance - 120   # bought a recharge card
print("After:", balance)
Before: 500 After: 380
Remember: Anything after # is a comment. Python ignores it completely; it is a note for humans (including future-you) reading the code.
Common mistake: = 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, Age and AGE are three different variables.
  • You cannot use Python keywords such as if, for, while, class, True.
โœ… ValidโŒ InvalidReason it fails
my_agemy ageSpace is not allowed
total11totalCannot start with a number
_namena@meSpecial symbol not allowed
roll_noforReserved keyword
total_markstotal-marks- is read as minus
Good habit: Name the variable after what it holds. x = 85 tells you nothing next week; math_marks = 85 tells you everything. Professionals write code for humans to read.
Exam tip: "Write any two rules for naming a variable" is a common 2-mark question. Memorise: cannot start with a number and no spaces or special symbols.

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:

Python
name = input("Enter your name: ")
age = int(input("Enter your age: "))    # text -> number

print("Namaste,", name)
print("Next year you will be", age + 1)
Enter your name: Ram Enter your age: 15 Namaste, Ram Next year you will be 16

A real one: the momo shop bill.

Python
plates = int(input("How many plates of momo? "))
rate = 180

total = plates * rate
print("Total bill: Rs.", total)
How many plates of momo? 3 Total bill: Rs. 540
Common mistake: Forget int() and age + 1 crashes with TypeError. Worse, plates * rate would silently print the text three times instead of multiplying. Always convert before calculating.
๐ŸŽฎ Try it yourself: Write a program that asks for the price of one exercise copy and how many you want, then prints the total. Add Rs. 20 delivery charge.

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 { }.

Python
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.")
Sita scored 92 marks. Sita scored 92 marks. Out of 100, Sita lost 8 marks.

You can also control decimal places, which is exactly what you need for money and percentages:

Python
total = 247
percent = total / 3

print(f"Percentage: {percent}")        # ugly
print(f"Percentage: {percent:.2f}%")   # 2 decimal places
Percentage: 82.33333333333333 Percentage: 82.33%
Common mistake: Forgetting the f. print("{name} scored") prints the braces literally instead of the value.

6 Operators in Python

An operator is a symbol that performs an operation on values. The values it works on are called operands.

Arithmetic Operators

OperatorMeaningExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division (always decimal)5 / 22.5
//Floor division (drops decimal)5 // 22
%Modulus (remainder)5 % 21
**Power5 ** 225
Where // 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.

OperatorMeaningExampleResult
==Equal to40 == 40True
!=Not equal to40 != 32True
>Greater than90 > 40True
<Less than90 < 40False
>=Greater than or equal40 >= 40True
<=Less than or equal39 <= 40True

Logical Operators

and needs both sides true. or needs at least one side true. not flips the answer.

Python
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?
False True True

Assignment and Membership Operators

Python
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)
12 True True
Exam tip: The difference between /, // 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.

A conditional statement runs a block of code only when a given condition is True. Python uses if, elif (else-if) and else.
Python
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")
Enter your marks: 75 Grade A

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.

Python
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
You can vote. Bring your ID. Program finished.
Common mistake: Two errors cause most beginner pain here: forgetting the : at the end of the if line, and mixing tabs with spaces. Pick 4 spaces and stay consistent.
๐ŸŽฎ Try it yourself: Write a program that asks for a number and prints "Even" or "Odd" using %. 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.

A loop (iteration) repeats a block of code again and again while a condition is satisfied, so we do not have to write the same lines many times.

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.

Python
# The 7 times table
for i in range(1, 6):
    print(f"7 x {i} = {7 * i}")
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35

A for loop can also walk through a list, one item at a time:

Python
students = ["Sita", "Ram", "Gita"]

for student in students:
    print("Present:", student)
Present: Sita Present: Ram Present: Gita

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.

Python
balance = 500

while balance >= 180:
    balance = balance - 180
    print("Bought 1 plate of momo. Left: Rs.", balance)

print("Not enough money now. Rs.", balance)
Bought 1 plate of momo. Left: Rs. 320 Bought 1 plate of momo. Left: Rs. 140 Not enough money now. Rs. 140

break and continue

Python
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=" ")
1 2 3 5 6
Pointfor loopwhile loop
Use whenNumber of repeats is knownOnly the stop condition is known
CounterHandled automatically by range()You must change it yourself
Typical useTables, lists, fixed countsMenus, games, "keep asking until correct"
Common mistake: In a 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.
๐ŸŽฎ Try it yourself: Print all even numbers from 1 to 20 in one line. Hint: 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.

A data structure is a way of storing and organising many values together under a single variable name so they can be handled easily.
StructureSymbolKey pointExample
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}
Python
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)
[55, 90, 70] (2065, 7, 12) {'name': 'Ram', 'age': 15} {8, 12, 5}
How to choose: Marks of students that may be corrected โ†’ list. A date of birth that must never change โ†’ tuple. A student's details with labels โ†’ dictionary. A list of unique districts visited โ†’ set.

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.

A list stores many values in a single variable, written inside square brackets [ ], separated by commas. It is ordered and changeable.
Item"apple""banana""orange"
Index (forward)012
Index (backward)-3-2-1
Python
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)
apple orange ['apple', 'banana'] ['apple', 'mango', 'orange']
Remember: The first item is 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.
๐ŸŽฎ Try it yourself: Make a list of your five favourite subjects and print the second one, the last one, and the first three together.

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.

FunctionWhat it doesExample on [55, 90, 70]
len(list)Counts the items3
sum(list)Adds all numbers215
max(list)Largest value90
min(list)Smallest value55
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:

Python
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)
Subjects : 4 Total : 255 Highest : 90 Lowest : 40 Average : 63.75 [40, 55, 70, 90, 100]
Exam tip: 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.

A dictionary stores data as key : value pairs inside curly braces { }. The value is found using its key instead of a number index.
Python
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)
Sita {'name': 'Sita', 'age': 17, 'class': 10, 'city': 'Pokhara'}

A phonebook is the most natural example of all:

Python
phonebook = {
    "Aama": "9841000001",
    "Buwa": "9841000002",
    "School": "014400000"
}

who = "Buwa"
print(f"{who}'s number is {phonebook[who]}")
Buwa's number is 9841000002
Common mistake: Asking for a key that does not exist (phonebook["Didi"]) causes a KeyError and the program stops. Use .get() instead: it returns None quietly. See the next topic.
PointListDictionary
Written with[ ]{ }
Accessed byNumber index (0, 1, 2 ...)Key (a name you choose)
Best forA simple sequence of valuesValues that need labels
Example[80, 95]{"Ram": 80, "Sita": 95}

13 Built-in Dictionary Functions

FunctionWhat 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
Python
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)
Ram None dict_keys(['name', 'age', 'class']) dict_values(['Ram', 15, 10]) Pairs: 3 {'name': 'Ram', 'class': 10}

Looping through a dictionary with .items() is how you print a whole marksheet in three lines:

Python
marksheet = {"Nepali": 78, "English": 65, "Math": 92}

for subject, mark in marksheet.items():
    print(f"{subject:10} : {mark}")

print("Total:", sum(marksheet.values()))
Nepali : 78 English : 65 Math : 92 Total: 235
๐ŸŽฎ Try it yourself: Build a dictionary of five district names and their famous food, then print each pair with a loop.

14 String Manipulation

Text is everywhere in real programs: names, addresses, passwords, search boxes. Python gives ready-made tools to clean and change text.

FunctionUseExample โ†’ 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 characterslen("Nepal") โ†’ 5
count()Count one letter"banana".count("a") โ†’ 3
Python
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(" "))
TECHNOLOGY CHANNEL technology channel Length: 18 Number of 'n': 3 Technology Nepal ['Technology', 'Channel']

A tiny real use: making a clean username from a messy typed name.

Python
full_name = "  Sita   Sharma  "

clean = full_name.strip().lower().replace("   ", "_")
print("Username:", clean)
Username: sita_sharma

Useful number functions too

Python
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
7 32 3.68 0xff
Remember: String functions do not change the original text; they return a new one. text.upper() only helps if you print it or store it: text = text.upper().

15 Library Function vs User-Defined Function

A function is a named block of code that performs one particular job and can be called again and again whenever that job is needed.

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.

PointLibrary (Built-in) FunctionUser-Defined Function
Who wrote itThe Python developersYou, the programmer
How to useJust call itFirst define it with def, then call it
PurposeCommon, general jobsYour program's own special job
Examplesprint(), len(), sum(), max()def calculate_grade(marks):
Python
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))
235 240
Exam tip: "Differentiate between library function and user-defined function" is a favourite 2-mark question. One line each: built-in, ready-made by Python vs created by the programmer using 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.

Exam tip: Any two of reusability, less code, easy to modify, easy to read will earn full marks.

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.
Python
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)
Sum is 8

Something more useful. This one function now decides every grade in your whole program:

Python
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))
Sita: A+ Ram : Fail Gita: A
Common mistake: Defining a function but never calling it. def only teaches Python the recipe; nothing cooks until you write grade(92).

18 Parameters and Arguments

A parameter is the variable written inside the brackets when the function is defined. An argument is the actual value passed inside the brackets when the function is called.

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.

Python
def greet(name):          # 'name' is the PARAMETER
    print("Namaste,", name)

greet("Sita")             # "Sita" is the ARGUMENT
greet("Ram")
Namaste, Sita Namaste, Ram
ParameterArgument
Written in the function definitionWritten in the function call
Just a placeholder nameA real value
def greet(name):greet("Sita")
Common mistake: Passing the wrong number of arguments. If a function has two parameters, you must give it exactly two arguments, or Python raises a TypeError.

19 Scope of Variables (Local & Global)

The scope of a variable is the part of the program where that variable can be used.
  • 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).

Python
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
Welcome to Shree Janata School Shree Janata School
PointLocal variableGlobal variable
CreatedInside a functionOutside all functions
UsableOnly inside that functionAnywhere in the program
LifetimeDestroyed when the function endsLives until the program ends
Common mistake: Trying to print a local variable outside its function gives 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

Python
def square(n):
    return n * n

area = square(4)      # the returned value is stored
print(area)
16

2. Returning nothing (None)

Python
def greet():
    print("Hello!")      # it does a job, but returns nothing

x = greet()
print("Returned value:", x)
Hello! Returned value: None

3. Returning many values

Python
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)
14 6 40
Common mistake: 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:

1๏ธโƒฃ

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.

Python
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
Sita - Nepal Ram - India Gita - USA
Rule to remember: Parameters with a default value must be written after the ones without. 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.

A library is a collection of ready-made code (modules and functions) that we can import into our program and use directly.
PointStandard LibraryExternal Library
AvailabilityComes with Python automaticallyMust be installed using pip
Cost of useJust import itInstall once, then import
Examplesmath, random, os, datetime, csv, turtlenumpy, 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.

Why this matters: A weather-prediction program in Nepal is written by someone who imports these libraries, not by someone who writes the maths from zero. Knowing which library to reach for is the skill.

23 Python Packages

A module is a single .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:

Terminal / Command Prompt
pip install numpy
pip install pandas matplotlib
Common mistake: Typing 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:

Python
# 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)
5.0 6.0 3.141592653589793
WayHow you call itBest when
import mathmath.sqrt(25)You need several functions from it
from math import sqrtsqrt(25)You need only one or two
import math as mm.sqrt(25)The name is long, e.g. pandas as pd
Common mistake: Using 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

Python
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
7.0 16.0 120 6 5 4

random module: dice, lotteries and quizzes

Python
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)
4 Sita ['Gita', 'Ram', 'Sita']
Note: 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

Python
import datetime

today = datetime.date.today()
print("Today is:", today)
print("Year:", today.year)
Today is: 2026-08-12 Year: 2026

pandas: data in neat tables

Python
import pandas as pd

data = {"Name": ["Ram", "Sita"], "Marks": [80, 95]}
df = pd.DataFrame(data)

print(df)
print("Average marks:", df["Marks"].mean())
Name Marks 0 Ram 80 1 Sita 95 Average marks: 87.5
๐ŸŽฎ Try it yourself: Build a dice game: roll two dice with 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.

CommandWhat 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
Python
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.

ShapeSidesAngle to turn
Trianglerange(3)120
Squarerange(4)90
Pentagonrange(5)72
Hexagonrange(6)60
Circle-ishrange(360)1
๐ŸŽฎ Try it yourself: Draw a colourful star with this two-line change: use 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.
Note: Turtle opens a separate drawing window, so it runs on a computer with Python installed. Most online editors cannot show it.

27 Matplotlib & Data Visualisation

Data visualisation is showing data as a picture (chart or graph) so that patterns become obvious at a glance. Matplotlib is Python's most popular library for it.

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

Python
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

Python
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

Python
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()
ChartUse it when you want to show
Bar chartComparison between separate categories
Line chartA change or trend over time
Pie chartParts of one whole (percentages)
Scatter plotRelationship between two quantities
Remember: Nothing appears until you call plt.show(). Also install it first with pip install matplotlib. Related tools: Seaborn for prettier statistical charts and Plotly for interactive ones.
๐ŸŽฎ Try it yourself: Plot the marks of five friends as a bar chart, then change 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.

An error is a problem that stops the program. An exception is an error that happens while the program is running, and it can be caught and handled so the program does not crash.
ErrorCauseExample
SyntaxErrorWrong grammarMissing : after if
NameErrorUsing an undefined variableprint(mark) when you typed marks
TypeErrorMixing incompatible types"5" + 5
ValueErrorRight type, wrong valueint("abc")
ZeroDivisionErrorDividing by zero10 / 0
IndexErrorIndex outside the list[1, 2][5]
KeyErrorDictionary key not foundd["missing"]
IndentationErrorWrong spacingLine 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.

Python
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.")
Enter a number: 0 Error: cannot divide by zero! Thank you for using this program.
BlockWhen it runs
tryAlways: it holds the risky code
exceptOnly if that particular error happens
elseOnly if no error happened
finallyAlways, error or not (used for clean-up)
Exam tip: "Difference between error and exception" and "what is the use of try-except" are common questions. Short answer: an exception is a run-time error, and try-except lets the program handle it gracefully instead of crashing.

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.

File handling is the process of creating, opening, reading, writing and closing files from a program, so that data is stored permanently. Files are opened with open("filename", "mode").
ModeNameWhat it doesIf the file is missing
"r"ReadOpens the file only to read itError
"w"WriteWrites, erasing everything already insideCreates it
"a"AppendAdds to the end, keeping the old contentCreates it
"x"CreateCreates a brand-new fileError if it already exists
Warning worth memorising: "w" deletes the existing content the moment the file is opened, before you write a single character. When you mean "add more", use "a".
Real example: A hostel attendance program uses "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

Python
f = open("notes.txt", "w")
f.write("Hello from Python!\n")
f.write("This is line two.")
f.close()
print("File saved.")
File saved.

2. Read a file

Python
f = open("notes.txt", "r")
content = f.read()
f.close()
print(content)
Hello from Python! This is line two.

3. Update (append more)

Python
f = open("notes.txt", "a")
f.write("\nA new line added later.")
f.close()

print(open("notes.txt").read())
Hello from Python! This is line two. A new line added later.

4. Delete a file

Python
import os

os.remove("notes.txt")
print("File deleted.")
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.

Python
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)
Aaja Python sikeko din.
Remember: \n means "start a new line". Without it, everything you write gets stuck together on one long line.

31 CSV Read & Write

A CSV (Comma-Separated Values) file stores data in rows and columns as plain text, with commas between the values. It is the simplest way to exchange table data, and Excel opens it directly.

A CSV of student marks is literally just this text:

students.csv
Name,Marks
Ram,80
Sita,95

Write a CSV

Python
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.")
CSV written.

Read a CSV

Python
import csv

with open("students.csv", "r") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)
['Name', 'Marks'] ['Ram', '80'] ['Sita', '95']
Common mistake: Everything read from a CSV is text. Notice '80' in quotes above. To add marks up you must convert: int(row[1]).

Reading it back and calculating properly:

Python
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)
Total marks: 175
๐ŸŽฎ Try it yourself: Open the 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

Python
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))
A+ B Fail

Step 2: Collect the marks

Python
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

Python
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"])
Student name: Sita Nepali marks: 85 English marks: 90 Math marks: 95 Student name: Ram Nepali marks: 60 English marks: 50 Math marks: 50 ------ RESULT SHEET ------ Sita 270 90.00% A+ Ram 160 53.33% C Topper: Sita

Step 4: Save it forever (CSV)

Python
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 saved to result.csv
Why divide by 3? Each subject is out of 100, so three subjects total 300. Percentage = (Total รท 300) ร— 100, which simplifies to Total รท 3. Change the subject count and this formula changes with it.
๐Ÿ† What you just built: A working result system. Swap "students" for "customers" and "marks" for "prices" and the very same code becomes a shop billing system. That is programming: one pattern, endless uses.
๐ŸŽฎ Level up: (1) Ask how many students instead of fixing it at 2. (2) Refuse marks above 100 or below 0. (3) Show a bar chart of everyone's total with matplotlib. (4) Read 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

Variable
A name that stores a value in memory.
Keyword
A reserved word like if, for, def that cannot be used as a name.
Comment
A note after # that Python ignores.
print()
Shows output on the screen.
input()
Takes input from the user, always as text.
Indentation
The spaces that show which lines belong to a block.
Operator
A symbol that performs an operation, e.g. + or %.
Modulus (%)
Gives the remainder after division.
f-string
Text with variables inserted using f"{ }".
Loop
Repeats a block of code many times.
Infinite loop
A loop whose condition never becomes false.
List
Ordered, changeable collection written in [ ].
Tuple
Ordered collection in ( ) that cannot be changed.
Dictionary
Key:value pairs stored in { }.
Index
The position of an item, starting from 0.
Function
Reusable named block of code that does one job.
Parameter
Variable written in the function definition.
Argument
Actual value passed when calling a function.
return
Sends a result back from a function.
Local variable
Created inside a function; usable only there.
Global variable
Created outside functions; usable anywhere.
Module
A single .py file containing functions.
Package
A folder grouping related modules.
Library
Ready-made code we import and use.
pip
Tool that installs external Python packages.
Exception
An error that occurs while the program is running.
File handling
Storing and reading data in files permanently.
CSV
Plain-text file storing table data separated by commas.

๐Ÿ”ค Full Forms (Click "Reveal" to check)

CSV Comma-Separated Values
IDE Integrated Development Environment
IDLE Integrated Development and Learning Environment
pip Pip Installs Packages
GCD Greatest Common Divisor
NumPy Numerical Python
Pandas Panel Data (Python Data Analysis Library)
AI Artificial Intelligence
ML Machine Learning
int Integer (whole number data type)
str String (text data type)
bool Boolean (True / False data type)
def Define (keyword used to create a function)

โœ… Choose the Correct Answer (MCQ)

1. Who created the Python programming language?
A James Gosling
B Guido van Rossum
C Dennis Ritchie
D Bjarne Stroustrup
2. Which function is used to show output in Python?
A input()
B print()
C show()
D echo()
3. What does input() always return?
A Integer
B String
C Float
D Boolean
4. Which of these is an invalid variable name?
A _total
B roll_no
C 2marks
D marks2
5. What is the result of 7 // 2?
A 3.5
B 3
C 1
D 4
6. Which symbol gives the remainder (modulus)?
A /
B //
C %
D **
7. Python uses which of the following to group a block of code?
A Curly braces { }
B Indentation (spaces)
C begin and end
D Semicolons
8. How many times will for i in range(1, 5): repeat?
A 5
B 4
C 3
D 6
9. What is the index of the first item in a list?
A 0
B 1
C -1
D 10
10. Which data structure cannot be changed after it is created?
A List
B Tuple
C Dictionary
D Set
11. A dictionary stores data as:
A Only values
B Key : value pairs
C Numbers only
D Index numbers only
12. Which keyword is used to create a function?
A func
B function
C def
D define
13. A variable created inside a function is called a:
A Local variable
B Global variable
C Public variable
D Static variable
14. Which command installs an external package?
A import pandas
B pip install pandas
C install pandas
D get pandas
15. Which library is used to draw charts and graphs?
A math
B random
C matplotlib
D turtle
16. Which file mode adds data at the end without erasing the old content?
A "r"
B "w"
C "a"
D "x"
17. int("abc") raises which error?
A ValueError
B NameError
C ZeroDivisionError
D IndexError
18. Which block of code runs whether an error happens or not?
A try
B except
C else
D finally

๐Ÿ”ฎ Predict the Output (think first, then reveal)

1 What will this print?
Python
a = 17
b = 5
print(a / b, a // b, a % b)
Answer: 3.4 3 2 โ€” / always gives a decimal, // drops the decimal part, % gives the remainder.
2 What will this print?
Python
marks = [40, 55, 90]
print(marks[1], marks[-1], len(marks))
Answer: 55 90 3 โ€” index 1 is the second item because counting starts at 0, and -1 means the last item.
3 What will this print?
Python
for i in range(1, 6):
    if i == 3:
        continue
    print(i, end=" ")
Answer: 1 2 4 5 โ€” continue skips only that one turn of the loop; it does not stop the loop.
4 What will this print?
Python
def add(a, b=10):
    return a + b

print(add(5), add(5, 20))
Answer: 15 25 โ€” the first call uses the default b = 10, the second replaces it with 20.
5 What will this print?
Python
text = "Nepal"
print(text.upper())
print(text)
Answer: 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)

1 Why does this crash?
Python
age = input("Enter age: ")
print("Next year:", age + 1)
Bug: input() returns text, so Python cannot add 1 to it (TypeError).
Fix: age = int(input("Enter age: "))
2 Why does this never stop?
Python
count = 1
while count <= 5:
    print(count)
Bug: count is never increased, so the condition stays true forever (infinite loop).
Fix: add count = count + 1 inside the loop.
3 Why is there a syntax error?
Python
marks = 80
if marks >= 40
    print("Pass")
Bug: the colon is missing at the end of the if line.
Fix: if marks >= 40:
4 Why does this print nothing useful?
Python
def total(a, b):
    print(a + b)

result = total(4, 6)
print("Result is", result)
Bug: the function prints the sum but does not return it, so result becomes None.
Fix: change print(a + b) to return a + b.
5 Why did the old content disappear?
Python
f = open("diary.txt", "w")
f.write("New entry")
f.close()
Bug: mode "w" erases everything already in the file.
Fix: use mode "a" to append instead.

โœ๏ธ Short Answer Questions

1 What is Python? Write any two features.
Answer: Python is a simple, high-level, general-purpose programming language created by Guido van Rossum in 1991. Features: its syntax is easy and English-like, it is free and open-source, it works on all operating systems, and it has a huge collection of libraries (any two).
2 What is a variable? Write any two rules for naming variables.
Answer: A variable is a name that stores a value in the computer's memory. Rules: it must start with a letter or underscore (never a number), and it cannot contain spaces or special symbols. Keywords also cannot be used (any two).
3 Why must we use int() with input() when taking a number?
Answer: 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.
4 Differentiate between /, // and % with an example.
Answer: / 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).
5 Why is indentation important in Python?
Answer: Python has no curly braces. It uses indentation (usually 4 spaces) to decide which lines belong inside an if, loop or function. Wrong indentation changes the meaning of the program or causes an IndentationError.
6 Differentiate between a for loop and a while loop.
Answer: A 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.
7 What is an infinite loop? How can it be avoided?
Answer: An infinite loop is a loop whose condition never becomes false, so it runs forever. It is avoided by making sure the variable used in the condition is updated inside the loop, for example count = count + 1.
8 Differentiate between a list and a dictionary.
Answer: A list stores items in order inside [ ] and each item is accessed by a number index. A dictionary stores key : value pairs inside { } and each value is accessed by its key.
9 Differentiate between a list and a tuple.
Answer: A list is written in [ ] 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.
10 What is a function? Write any two advantages.
Answer: A function is a named, reusable block of code that performs a specific job. Advantages: code can be reused, the program becomes shorter, it is easier to read, and a change needs to be made in only one place (any two).
11 Differentiate between a library function and a user-defined function.
Answer: A library (built-in) function is already provided by Python and can be used directly, such as print() or len(). A user-defined function is written by the programmer using the def keyword for a specific need.
12 Differentiate between a parameter and an argument.
Answer: A parameter is the variable written inside the brackets in the function definition. An argument is the actual value passed inside the brackets when the function is called.
13 What is the difference between a local and a global variable?
Answer: A local variable is created inside a function and can be used only inside that function. A global variable is created outside all functions and can be used anywhere in the program.
14 What is a module, a package and a library?
Answer: A module is a single .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.
15 What are the four file modes r, w, a and x?
Answer: "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.
16 What is an exception? Why do we use try and except?
Answer: An exception is an error that occurs while the program is running, such as ZeroDivisionError. try holds the risky code and except handles the error, so the program shows a friendly message instead of crashing.
17 Write a Python program to find the largest of three numbers.
Answer:
a = int(input("a: "))
b = int(input("b: "))
c = int(input("c: "))
print("Largest is", max(a, b, c))
18 Write a Python program to find the total and average of marks stored in a list.
Answer:
marks = [55, 90, 70, 40]
print("Total:", sum(marks))
print("Average:", sum(marks) / len(marks))

๐Ÿ› ๏ธ Practical Ideas (Try in the lab)

  1. Calculator: take two numbers and print their +, โˆ’, ร—, รท results.
  2. Even or Odd: ask for a number and use % to decide.
  3. Multiplication table: use a for loop to print the table of any number.
  4. Pass or fail: take marks of three subjects and print the grade using a function.
  5. Marks list: store 5 marks in a list and print the total, highest, lowest and average.
  6. Phonebook: use a dictionary of name : number and look up a contact by name.
  7. Momo bill: ask how many plates and print the bill with 13% VAT added.
  8. Guess the number: use random.randint(1, 10) and a while loop to let the user keep guessing.
  9. Turtle art: draw a square, a triangle and a five-pointed star using loops.
  10. Bar chart: plot your subject marks using matplotlib.
  11. Save & read: write your name and class to a text file, then read it back.
  12. Attendance CSV: save five classmates' names and attendance to a CSV, then count how many were present.