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!

How to run these: Install Python from 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.

Python is a simple, easy-to-read, general-purpose programming language used for web development, data science, artificial intelligence, automation and more.

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:

Python
print("Hello, Nepal!")
print("Welcome to Python programming.")
Hello, Nepal! Welcome to Python programming.
Note: print() is used to show output on the screen. Whatever is inside the quotes is displayed exactly.

2 Python Variables

A variable is a name that stores a value in the computer's memory, so we can use and change it later.

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.

Python
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)
Sita 16 5.4 True
Tip: Anything after a # 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: age and Age are different.
  • You cannot use Python keywords (like if, for, print) as names.
โœ… ValidโŒ InvalidReason
my_agemy ageSpace not allowed
total11totalCannot start with number
_namena@meSpecial symbol not allowed
roll_noforKeyword 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().

Python
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)
Enter your name: Ram Enter your age: 15 Hello Ram Next year you will be 16
Common mistake: If you forget 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).

Python
name = "Sita"
marks = 92

# f-string (recommended)
print(f"{name} scored {marks} marks.")

# .format() method
print("{} scored {} marks.".format(name, marks))
Sita scored 92 marks. Sita scored 92 marks.
Why use it: f-strings are short and clear. You can even do maths inside: f"Total = {10 + 5}" gives Total = 15.

6 Operators in Python

Operators are symbols that do operations on values.

Arithmetic Operators

OperatorMeaningExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/Division5 / 22.5
//Floor division5 // 22
%Remainder (modulus)5 % 21
**Power5 ** 225

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).

Python
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
13 1 1000 True False True

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.

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
Very important: The lines inside 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.

Python
for i in range(1, 6):
    print("Number:", i)
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5

While Loop

Best when you repeat until a condition becomes false.

Python
count = 1
while count <= 3:
    print("Hello", count)
    count = count + 1
Hello 1 Hello 2 Hello 3
Warning: In a while loop, always change the variable (e.g. count = count + 1), otherwise the loop never stops (infinite loop).

9 Data Structures in Python

A data structure is a way of storing and organising many values together under one name.

Python has four main built-in data structures:

StructureSymbolKey PointExample
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.

Python
fruits = ["apple", "banana", "orange"]

print(fruits[0])        # first item
print(fruits[-1])       # last item

fruits[1] = "mango"     # change an item
print(fruits)
apple orange ['apple', 'mango', 'orange']
Remember: Index starts at 0, so the first item is fruits[0] and fruits[-1] means the last item.

11 Built-in List Functions

Python gives ready-made functions to work with lists.

FunctionWhat 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
Python
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)
Count: 4 Total: 255 Highest: 90 Lowest: 40 [25, 55, 90, 70, 40, 100]

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.

Python
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)
Sita {'name': 'Sita', 'age': 17, 'class': 10, 'city': 'Pokhara'}

13 Built-in Dictionary Functions

FunctionWhat 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
Python
student = {"name": "Ram", "age": 15, "class": 10}

print(student.get("name"))
print(student.keys())
print(student.values())

del student["age"]
print(student)
Ram dict_keys(['name', 'age', 'class']) dict_values(['Ram', 15, 10]) {'name': 'Ram', 'class': 10}

14 String Manipulation

Python has many built-in tools to work with text and numbers.

FunctionUseExample โ†’ Result
upper()UPPERCASE"ram".upper() โ†’ RAM
lower()lowercase"RAM".lower() โ†’ ram
len()Length / count of characterslen("Nepal") โ†’ 5
count()Count a letter"banana".count("a") โ†’ 3
abs()Absolute (positive) valueabs(-7) โ†’ 7
pow()Powerpow(2, 3) โ†’ 8
round()Round a decimalround(3.67) โ†’ 4
hex()Convert to hexadecimalhex(255) โ†’ 0xff
Python
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))
TECHNOLOGY CHANNEL technology channel Length: 18 Number of 'n': 3 10 32 0xff

15 Library Function vs User-Defined Function

A function is a block of code that does a particular job and can be used (called) again and again.

There are two kinds:

Library (Built-in) FunctionUser-Defined Function
Already made by PythonMade by the programmer
Just call and use itYou 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.
Python
def add(a, b):        # def + name + parameters
    result = a + b
    return result     # return type

answer = add(5, 3)    # function call
print("Sum is", answer)
Sum is 8

18 Parameters and Arguments

A parameter is the variable written in the function definition. An argument is the actual value you pass when calling the function.
Python
def greet(name):       # 'name' is a PARAMETER
    print("Namaste,", name)

greet("Sita")          # "Sita" is an ARGUMENT
greet("Ram")
Namaste, Sita Namaste, 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.
Python
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
Welcome to ABC School ABC School

20 Return Values: One, None or Many

Function returning a value

Python
def square(n):
    return n * n

print(square(4))     # uses the returned value
16

Function NOT returning a value

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

greet()
Hello!

Returning multiple values (as a list/tuple)

Python
def calc(a, b):
    return a + b, a - b, a * b   # returns three values

total, diff, product = calc(10, 4)
print(total, diff, product)
14 6 40

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.
Python
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
Sita - Nepal Ram - India Gita - USA

22 Libraries in Python

A library is a collection of ready-made code (functions and modules) that we can import and use, so we do not have to write everything ourselves.

There are two kinds:

Standard LibraryExternal Library
Comes with Python automaticallyMust be installed using pip
math, random, os, datetimematplotlib, pandas, numpy, scipy, scikit-learn
External libraries: NumPy (fast maths on numbers), Pandas (tables/data), Matplotlib (charts), SciPy (science maths), Scikit-learn (machine learning).

23 Python Packages

A package is a folder that groups many related modules (Python files) together. A module is a single .py file with functions inside.

External packages are installed with pip (Python's package installer):

Terminal / Command Prompt
pip install numpy
pip install pandas matplotlib
Note: Run 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:

Python
# 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)
5.0 6.0 3.141592653589793

25 Popular Libraries (with examples)

math module

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

random module

Python
import random

print(random.randint(1, 6))                  # like rolling a dice
print(random.choice(["Ram", "Sita", "Gita"])) # pick one randomly
4 Sita
Note: random gives different output each time you run it.

pandas (data tables)

Python
import pandas as pd

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

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.

Python
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()
Try it: Change range(4) to range(5) and the angle to 72 to draw a pentagon!
๐Ÿข
Image: Turtle drawing a square / star
Place your image here (filename: turtle-square.png)

27 Matplotlib & Data Visualisation

Matplotlib is the most popular library to draw charts and graphs from data.

Bar Chart

Python
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

Python
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()
Other tools: Seaborn (makes prettier statistical charts) and Plotly (makes interactive charts you can hover over) are also built on top of matplotlib ideas.
๐Ÿ“Š
Image: Bar chart of marks
Place your image here (filename: matplotlib-bar.png)

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.

ErrorCause
SyntaxErrorWrong grammar (e.g. missing :)
NameErrorUsing a variable not defined
ZeroDivisionErrorDividing a number by 0
ValueErrorWrong type of value (e.g. int("abc"))
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!")
Enter a number: 0 Error: cannot divide by zero!

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").

ModeMeaningWhat it does
"r"ReadOpens to read (file must exist)
"w"WriteCreates new / erases old content
"a"AppendAdds to the end, keeps old content
"x"CreateCreates a new file (error if it exists)
Real-world example: A school result program saves each student's marks to a file so they can be opened again tomorrow.

30 Write, Read, Update & Delete a File

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.

Read a file

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

Update (append more)

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

Delete a file

Python
import os
os.remove("notes.txt")
print("File deleted.")
File deleted.
Tip: Using 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

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']

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!

Python
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']}")
Enter student name: Ram Enter total marks: 85 Enter student name: Sita Enter total marks: 35 ----- RESULT ----- Ram: 85 marks -> Grade A Sita: 35 marks -> Grade Fail
Challenge: Change 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

Variable
A name that stores a value in memory.
print()
Shows output on the screen.
input()
Takes input from the user (as text).
List
Ordered, changeable collection in [ ].
Dictionary
Key:value pairs stored in { }.
Loop
Repeats a block of code many times.
Function
Reusable block of code that does a job.
Parameter
Variable in a function definition.
Argument
Actual value passed to a function.
Library
Ready-made code we import and use.
Module
A single .py file with functions.
Exception
An error that happens while running.

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

CSV Comma-Separated Values
IDE Integrated Development Environment
pip Pip Installs Packages
GCD Greatest Common Divisor
NumPy Numerical Python
AI Artificial Intelligence

โœ… Choose the Correct Answer (MCQ)

1. Which function is used to show output in Python?
A input()
B print()
C show()
D echo()
2. What does input() always return?
A Integer
B String
C Float
D Boolean
3. Which symbol is used for the remainder (modulus)?
A /
B //
C %
D **
4. What is the index of the first item in a list?
A 0
B 1
C -1
D 10
5. Which keyword is used to create a function?
A func
B function
C def
D define
6. A dictionary stores data as:
A Only values
B Key:value pairs
C Numbers only
D Index numbers
7. Which library is used to draw charts and graphs?
A math
B random
C matplotlib
D turtle
8. Which file mode adds data to the end without erasing?
A "r"
B "w"
C "a"
D "x"
9. Dividing a number by zero raises which error?
A ValueError
B NameError
C ZeroDivisionError
D SyntaxError
10. A variable made inside a function is called:
A Local variable
B Global variable
C Public variable
D Free variable

โœ๏ธ Short Answer Questions

1 What is a variable? Write any two rules for naming variables.
Answer: A variable is a name that stores a value in memory. Rules: it must start with a letter or underscore (not a number), and it cannot contain spaces or special symbols (any two).
2 Differentiate between a list and a dictionary.
Answer: A list stores items in order, accessed by a number index, written in [ ]. A dictionary stores key:value pairs, accessed by the key, written in { }.
3 Differentiate between a for loop and a while loop.
Answer: A for loop is used when we know how many times to repeat (it loops over a range/list). A while loop repeats as long as a condition is true, useful when we do not know the exact count.
4 What is a function? Write any two advantages.
Answer: A function is a reusable block of code that performs a specific job. Advantages: it makes code reusable, reduces repetition, keeps the program organised and easy to fix (any two).
5 Differentiate between a parameter and an argument.
Answer: A parameter is the variable listed in the function definition. An argument is the actual value passed to the function when it is called.
6 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 it. A global variable is created outside all functions and can be used anywhere in the program.
7 What are the four file modes r, w, a and x?
Answer: "r" reads an existing file; "w" writes (erases old content or creates new); "a" appends data to the end; "x" creates a new file and gives an error if it already exists.
8 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))

๐Ÿ› ๏ธ 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 say if it is even or odd.
  3. Multiplication table: use a for loop to print the table of any number.
  4. Marks list: store 5 marks in a list and print the total, highest and lowest.
  5. Phonebook: use a dictionary of name:number and look up a contact.
  6. Turtle art: draw a square, triangle and star using loops.
  7. Bar chart: plot your subject marks using matplotlib.
  8. Save & read: write your name and class to a text file, then read it back.