Chapter 4: Programming in Python
Learn to actually write code: variables, decisions, loops, lists, functions, libraries, files and charts. Every example below is copy-paste ready: try it in your own Python!
python.org, or use a free online editor like replit.com or programiz.com/python-programming/online-compiler. Click ๐ Copy on any code box, paste it, and run.
1 Introduction to Python
Python is a popular, high-level programming language created by Guido van Rossum in 1991. It is loved by beginners because its code reads almost like simple English. Big companies like Google, YouTube, Instagram and NASA use Python.
Why learn Python?
- Easy syntax: less code, more readable.
- Free and open-source.
- Huge libraries for AI, data, games and websites.
- Works everywhere: Windows, Mac, Linux.
Your very first program just prints a message on the screen:
print("Hello, Nepal!")
print("Welcome to Python programming.")
print() is used to show output on the screen. Whatever is inside the quotes is displayed exactly.
2 Python Variables
Think of a variable as a labelled box. In Python you create a variable just by giving it a name and a value with =. You do NOT need to write the data type.
name = "Sita" # text (string)
age = 16 # whole number (int)
height = 5.4 # decimal number (float)
is_student = True # True/False (bool)
print(name, age, height, is_student)
# is a comment. Python ignores it; it is only a note for humans.
3 Rules for Python Variables
You must follow these rules when naming a variable:
- A name can have letters, numbers and underscore (_).
- It must start with a letter or underscore, never a number.
- No spaces are allowed (use
_instead). - Names are case-sensitive:
ageandAgeare different. - You cannot use Python keywords (like
if,for,print) as names.
| โ Valid | โ Invalid | Reason |
|---|---|---|
my_age | my age | Space not allowed |
total1 | 1total | Cannot start with number |
_name | na@me | Special symbol not allowed |
roll_no | for | Keyword not allowed |
4 Input and Output in Python
print() shows output, and input() takes input from the user. Important: input() always gives text (string), so to do maths we convert it using int() or float().
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # convert text to number
print("Hello", name)
print("Next year you will be", age + 1)
int(), then age + 1 will give an error because text and numbers cannot be added.
5 String Formatting
String formatting lets us put variables neatly inside a sentence. The easiest modern way is the f-string (put f before the quotes).
name = "Sita"
marks = 92
# f-string (recommended)
print(f"{name} scored {marks} marks.")
# .format() method
print("{} scored {} marks.".format(name, marks))
f"Total = {10 + 5}" gives Total = 15.
6 Operators in Python
Operators are symbols that do operations on values.
Arithmetic Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 2 | 7 |
- | Subtraction | 5 - 2 | 3 |
* | Multiplication | 5 * 2 | 10 |
/ | Division | 5 / 2 | 2.5 |
// | Floor division | 5 // 2 | 2 |
% | Remainder (modulus) | 5 % 2 | 1 |
** | Power | 5 ** 2 | 25 |
Relational (Comparison) Operators
These compare two values and give True or False: == (equal), != (not equal), >, <, >=, <=.
Logical Operators
and (both true), or (at least one true), not (opposite).
a = 10
b = 3
print(a + b, a % b, a ** b) # arithmetic
print(a > b, a == b) # relational
print(a > 5 and b < 5) # logical
Other operators: assignment (=, +=, -=) and membership (in, not in) which check if a value is inside a list or string.
7 Conditional Statements (if, elif, else)
Conditional statements let the program make decisions. Python uses indentation (spaces) to know which lines belong to the if.
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")
if must be indented (usually 4 spaces). Wrong indentation causes an error in Python.
8 Iteration / Loops in Python
A loop repeats a block of code many times so we do not write it again and again.
For Loop
Best when you know how many times to repeat. range(1, 6) gives 1, 2, 3, 4, 5.
for i in range(1, 6):
print("Number:", i)
While Loop
Best when you repeat until a condition becomes false.
count = 1
while count <= 3:
print("Hello", count)
count = count + 1
while loop, always change the variable (e.g. count = count + 1), otherwise the loop never stops (infinite loop).
9 Data Structures in Python
Python has four main built-in data structures:
| Structure | Symbol | Key Point | Example |
|---|---|---|---|
| List | [ ] | Ordered, changeable | [10, 20, 30] |
| Tuple | ( ) | Ordered, fixed (cannot change) | (10, 20) |
| Dictionary | { } | Key : value pairs | {"name": "Ram"} |
| Set | { } | Unordered, no duplicates | {1, 2, 3} |
10 List
A list stores many values in one variable, written inside [ ]. Each item has a position called an index, starting from 0.
fruits = ["apple", "banana", "orange"]
print(fruits[0]) # first item
print(fruits[-1]) # last item
fruits[1] = "mango" # change an item
print(fruits)
fruits[0] and fruits[-1] means the last item.
11 Built-in List Functions
Python gives ready-made functions to work with lists.
| Function | What it does |
|---|---|
len(list) | Counts how many items |
list.append(x) | Adds x at the end |
list.insert(i, x) | Inserts x at position i |
sum(list) | Adds all numbers |
min(list) | Smallest value |
max(list) | Largest value |
marks = [55, 90, 70, 40]
print("Count:", len(marks))
print("Total:", sum(marks))
print("Highest:", max(marks))
print("Lowest:", min(marks))
marks.append(100) # add at end
marks.insert(0, 25) # add at start
print(marks)
12 Dictionary in Python
A dictionary stores data as key : value pairs inside { }. Instead of a number index, we use the key to get a value: just like a real dictionary where the word is the key and the meaning is the value.
student = {
"name": "Sita",
"age": 16,
"class": 10
}
print(student["name"]) # get value by key
student["age"] = 17 # change a value
student["city"] = "Pokhara" # add new pair
print(student)
13 Built-in Dictionary Functions
| Function | What it does |
|---|---|
dict.get(key) | Returns the value for a key (safe) |
dict.keys() | Returns all keys |
dict.values() | Returns all values |
del dict[key] | Removes a key:value pair |
student = {"name": "Ram", "age": 15, "class": 10}
print(student.get("name"))
print(student.keys())
print(student.values())
del student["age"]
print(student)
14 String Manipulation
Python has many built-in tools to work with text and numbers.
| Function | Use | Example โ Result |
|---|---|---|
upper() | UPPERCASE | "ram".upper() โ RAM |
lower() | lowercase | "RAM".lower() โ ram |
len() | Length / count of characters | len("Nepal") โ 5 |
count() | Count a letter | "banana".count("a") โ 3 |
abs() | Absolute (positive) value | abs(-7) โ 7 |
pow() | Power | pow(2, 3) โ 8 |
round() | Round a decimal | round(3.67) โ 4 |
hex() | Convert to hexadecimal | hex(255) โ 0xff |
text = "Technology Channel"
print(text.upper())
print(text.lower())
print("Length:", len(text))
print("Number of 'n':", text.count("n"))
print(abs(-10), pow(2, 5), hex(255))
15 Library Function vs User-Defined Function
There are two kinds:
| Library (Built-in) Function | User-Defined Function |
|---|---|
| Already made by Python | Made by the programmer |
| Just call and use it | You write it using def |
Examples: print(), len(), sum() | Example: def add(a, b): |
16 Advantages of Functions
Reusable
Write once, use many times.
Less Code
Avoids repeating the same lines.
Organised
Breaks a big problem into small parts.
Easy to Fix
Change code in one place only.
Readable
Program is easier to understand.
17 Creating a Function
We create a function using the def keyword. A function has four parts:
- def + name: defines and names the function.
- parameter list: inputs inside
( ). - return: sends a result back (optional).
- function call: the line that runs it.
def add(a, b): # def + name + parameters
result = a + b
return result # return type
answer = add(5, 3) # function call
print("Sum is", answer)
18 Parameters and Arguments
def greet(name): # 'name' is a PARAMETER
print("Namaste,", name)
greet("Sita") # "Sita" is an ARGUMENT
greet("Ram")
19 Scope of Variables (Local & Global)
The scope is the area where a variable can be used.
- Local variable: created inside a function; works only inside it.
- Global variable: created outside all functions; works everywhere.
school = "ABC School" # GLOBAL variable
def show():
msg = "Welcome" # LOCAL variable
print(msg, "to", school)
show()
print(school) # works (global)
# print(msg) # ERROR: msg is local
20 Return Values: One, None or Many
Function returning a value
def square(n):
return n * n
print(square(4)) # uses the returned value
Function NOT returning a value
def greet():
print("Hello!") # just does a job, returns nothing
greet()
Returning multiple values (as a list/tuple)
def calc(a, b):
return a + b, a - b, a * b # returns three values
total, diff, product = calc(10, 4)
print(total, diff, product)
21 Types of Function Arguments
There are three common types of arguments:
- Positional: matched by their order.
- Default: have a ready value if you do not pass one.
- Keyword: passed by name, so order does not matter.
def student(name, country="Nepal"): # country has a DEFAULT
print(name, "-", country)
student("Sita") # positional
student("Ram", "India") # positional override
student(country="USA", name="Gita") # keyword arguments
22 Libraries in Python
There are two kinds:
| Standard Library | External Library |
|---|---|
| Comes with Python automatically | Must be installed using pip |
math, random, os, datetime | matplotlib, pandas, numpy, scipy, scikit-learn |
23 Python Packages
.py file with functions inside.
External packages are installed with pip (Python's package installer):
pip install numpy
pip install pandas matplotlib
pip commands in the terminal/command prompt, NOT inside a Python program.24 Importing and Using Libraries
Before using a library, we import it. There are three common ways:
# 1. Import the whole module
import math
print(math.sqrt(25))
# 2. Import a specific function from a module
from math import sqrt
print(sqrt(36))
# 3. Import with a short nickname (alias)
import math as m
print(m.pi)
25 Popular Libraries (with examples)
math module
import math
print(math.sqrt(49)) # square root -> 7.0
print(math.pow(2, 4)) # power -> 16.0
print(math.factorial(5)) # 5! = 120
print(math.gcd(12, 18)) # GCD -> 6
print(math.log(100, 10)) # log base 10 -> 2.0
random module
import random
print(random.randint(1, 6)) # like rolling a dice
print(random.choice(["Ram", "Sita", "Gita"])) # pick one randomly
random gives different output each time you run it.pandas (data tables)
import pandas as pd
data = {"Name": ["Ram", "Sita"], "Marks": [80, 95]}
df = pd.DataFrame(data)
print(df)
26 Turtle Graphics
The turtle library lets you draw shapes by moving a little "turtle" pen on the screen. It is great fun for learning loops.
import turtle
pen = turtle.Turtle()
# draw a square
for i in range(4):
pen.forward(100) # move 100 steps
pen.right(90) # turn 90 degrees
turtle.done()
range(4) to range(5) and the angle to 72 to draw a pentagon!27 Matplotlib & Data Visualisation
Matplotlib is the most popular library to draw charts and graphs from data.
Bar Chart
import matplotlib.pyplot as plt
subjects = ["Maths", "Science", "English"]
marks = [85, 92, 78]
plt.bar(subjects, marks, color="teal")
plt.title("My Marks")
plt.xlabel("Subject")
plt.ylabel("Marks")
plt.show()
Scatter Plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 14, 9, 18, 20]
plt.scatter(x, y, color="red")
plt.title("Scatter Plot Example")
plt.show()
28 Errors and Exceptions
An error stops the program. An exception is an error that happens while running. We can handle it safely using try and except so the program does not crash.
| Error | Cause |
|---|---|
SyntaxError | Wrong grammar (e.g. missing :) |
NameError | Using a variable not defined |
ZeroDivisionError | Dividing a number by 0 |
ValueError | Wrong type of value (e.g. int("abc")) |
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!")
29 File Handling & Modes
File handling lets a program save data permanently in a file, so it is not lost when the program closes. We open a file using open("filename", "mode").
| Mode | Meaning | What it does |
|---|---|---|
"r" | Read | Opens to read (file must exist) |
"w" | Write | Creates new / erases old content |
"a" | Append | Adds to the end, keeps old content |
"x" | Create | Creates a new file (error if it exists) |
30 Write, Read, Update & Delete a File
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.")
Read a file
f = open("notes.txt", "r")
content = f.read()
f.close()
print(content)
Update (append more)
f = open("notes.txt", "a")
f.write("\nA new line added later.")
f.close()
Delete a file
import os
os.remove("notes.txt")
print("File deleted.")
with open(...) as f: closes the file automatically: it is the safer, modern way.31 CSV Read & Write
A CSV (Comma-Separated Values) file stores data in rows and columns, like a simple spreadsheet. Python has a built-in csv module.
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)
32 Mini Project: Student Marks System
This small project combines many topics: input, list, dictionary, loop, function and if-else. Copy it and run it!
def grade(total):
if total >= 90:
return "A+"
elif total >= 60:
return "A"
elif total >= 40:
return "Pass"
else:
return "Fail"
students = []
for i in range(2):
name = input("Enter student name: ")
marks = int(input("Enter total marks: "))
students.append({"name": name, "marks": marks, "grade": grade(marks)})
print("\n----- RESULT -----")
for s in students:
print(f"{s['name']}: {s['marks']} marks -> Grade {s['grade']}")
range(2) to ask for more students, and save the result to a CSV file using what you learned in Topic 31.๐ Exercises & Quiz
Test what you've learned! Click Show Answer to check yourself.
๐ Short Terms / Glossary
๐ค Full Forms (Click "Reveal" to check)
โ Choose the Correct Answer (MCQ)
โ๏ธ Short Answer Questions
a = int(input("a: "))b = int(input("b: "))c = int(input("c: "))print("Largest is", max(a, b, c))
๐ ๏ธ Practical Ideas (Try in the lab)
- Calculator: take two numbers and print their +, โ, ร, รท results.
- Even or Odd: ask for a number and use
%to say if it is even or odd. - Multiplication table: use a for loop to print the table of any number.
- Marks list: store 5 marks in a list and print the total, highest and lowest.
- Phonebook: use a dictionary of name:number and look up a contact.
- Turtle art: draw a square, triangle and 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.