Think of the jobs you do again and again: adding up the marks of forty students, checking whether a number is even, drawing the same shape twenty times. A computer will do them for you, a million times over and without one slip, if you can tell it exactly what to do. A program is that set of exact instructions, and Python is one of the easiest languages to write it in.
Python is not a toy. It runs parts of YouTube and Instagram, sorts the data of hospitals and banks, and helped make the first picture of a black hole in 2019. In this unit you will write your own functions, use libraries that other people have already written, draw with a turtle, catch errors before they crash your program, keep data in files, and turn numbers into charts.
To write and run (execute) a Python program, you need a Python interpreter: a program that reads your Python code and carries it out, line by line. You can install it on a computer from python.org, or use an online Python interpreter in a web browser. Python comes with a simple editor called IDLE. Its window where you type commands one at a time is called the Python shell. The shell shows the prompt >>>, waits for a command, runs it at once and shows the result:
>>> 2 + 35>>> print("Namaste")Namaste>>> 7 * 642The shell is good for trying out one line. For a longer program, open a new file in IDLE (File → New File), type the program, save it with a name ending in .py, and run it (Run → Run Module, or press F5). The output appears in the shell.
4.1 Revision of the basics of Python
Input and output
A program needs a way to show results (output) and a way to get data from the user (input). These are its input/output (I/O) statements.
The print() function shows on the screen whatever you put inside its brackets: text in quotes, numbers, variables, or calculations.
print("Hello, Python!")print("The answer is", 6 * 7)Output
Hello, Python!The answer is 42Things separated by commas are printed with one space between them, and each print() ends by moving to a new line. Two extra settings change that: sep sets what goes between the things, and end sets what comes at the end.
print("2026", "10", "18", sep="-")print("No new line", end=" ")print("after this.")Output
2026-10-18No new line after this.The input() function shows a message (the prompt), waits for the user to type something and press Enter, and gives back what was typed. Store it in a variable to use it:
name = input("What is your name? ")print("Namaste,", name)Output
What is your name? SitaNamaste, SitaData types and variables
Data types
Every value in Python has a data type, which decides what kind of value it is and what you can do with it. The four basic ones:
| Data type | What it holds | Examples |
|---|---|---|
Integer (int) |
a whole number, positive, negative or zero, as large as you like | -3, 0, 42, 1000000 |
Float (float) |
a number with a decimal point | 3.14, -0.5, 1.567, 2.0 |
String (str) |
text: letters, digits, spaces and symbols, inside quotes | "hello", 'Python@', "Bhaktapur1" |
Boolean (bool) |
only one of two values, True or False |
is_student = True, has_mobile = False |
A string can be written in double quotes ("Nepal") or single quotes ('Nepal'); both mean the same. A Python integer has no fixed largest value: 2 ** 100 works out exactly. The function type() tells you a value’s data type:
>>> type(42)<class 'int'>>>> type(42.0)<class 'float'>>>> type("42")<class 'str'>>>> type(True)<class 'bool'>Which of these is not a data type in Python?
Pick an answer to see why.
Variables and identifiers
A variable is a name that holds a value, like a label stuck on a box. A variable is made the moment a value is assigned to it with =:
a = 15school = "Shree Janak Secondary School"a = a + 5 # a now holds 20The = sign in Python doesn’t mean “equals” as in mathematics. It means “work out the right side, then put the result in the variable on the left”. That is why a = a + 5 makes sense: take the 15 in a, add 5, and put 20 back in a.
An identifier is any name you make up for something in a program: a variable, a function, a class. Python’s rules for identifiers:
- It can contain letters, digits and the underscore
_, but it can’t start with a digit (mark1is fine,1markis not). - No spaces or symbols:
total_marksis fine,total marksandtotal-marksare not. - It can’t be a keyword, one of Python’s own words such as
if,for,def,Trueorimport. - Capital and small letters are different:
Ageandageare two different variables.
Good identifiers say what they hold: total_marks tells you more than t.
Operators and expressions
An operator is a symbol that does something with values, such as + or >. The values it works on are its operands, and a combination of values, variables and operators that works out to one value, such as price * 3 + 50, is an expression.
1. Arithmetic operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ |
Addition | 10 + 20 |
30 |
- |
Subtraction | 10 - 20 |
-10 |
* |
Multiplication | 10 * 20 |
200 |
/ |
Division | 20 / 8 |
2.5 |
% |
Modulus (remainder) | 20 % 8 |
4 |
** |
Exponent (power) | 2 ** 3 |
8 |
// |
Floor division | 20 // 8 |
2 |
/ always gives a float, even when the division is exact: 20 / 10 is 2.0, not 2. // divides and rounds down to a whole number (floor division), so it gives an integer for two integers: 20 // 8 is 2, and -7 // 2 is −4, not −3. % gives the remainder, which is how a program tests whether a number is even (n % 2 == 0) or takes the last digit of a number (n % 10).
When an expression has several operators, Python works out ** first, then *, /, // and %, then + and -, from left to right; brackets come before all of them. So 2 + 3 * 4 is 14, but (2 + 3) * 4 is 20.
What does print(17 // 5, 17 % 5) show?
Pick an answer to see why.
2. Relational operators
Relational (comparison) operators compare two values. The answer is always a Boolean: True or False.
| Name | Operator | True when… | Example | Result |
|---|---|---|---|---|
| Equal to | == |
both are the same | 5 == 5 |
True |
| Not equal to | != |
they are different | 3 != 5 |
True |
| Greater than | > |
the left is bigger | 7 > 5 |
True |
| Less than | < |
the left is smaller | 3 < 9 |
True |
| Greater than or equal to | >= |
bigger or the same | 8 >= 8 |
True |
| Less than or equal to | <= |
smaller or the same | 4 <= 6 |
True |
3. Logical operators
Logical operators join conditions, to make decisions that depend on more than one thing.
| Operator | Gives True when… |
Example (with a = 8) |
Result |
|---|---|---|---|
and |
both conditions are true | a > 5 and a < 10 |
True |
or |
at least one is true | a < 5 or a == 8 |
True |
not |
the condition is false (it flips it) | not (a > 5) |
False |
Think of a bus seat for students: you get the discount if you are a student and you show your ID card. With or, either one would be enough.
4. Assignment operators
= is the assignment operator. Python also has short forms that change a variable using its own value:
| Operator | Example | Means the same as |
|---|---|---|
= |
x = 5 |
put 5 in x |
+= |
x += 3 |
x = x + 3 |
-= |
x -= 3 |
x = x - 3 |
*= |
x *= 3 |
x = x * 3 |
/= |
x /= 3 |
x = x / 3 |
%= |
x %= 3 |
x = x % 3 |
count += 1, “add one to the count”, is the line you will see most often in loops.
Conditional statements
A program often has to choose: pass or fail, positive or negative, adult or child. A conditional statement runs some lines only when a condition is true. Python has three forms: if, if-else and if-elif-else.
The if statement
if condition: # lines that run only when the condition is TrueThe line with if ends with a colon (:), and the lines that belong to it are indented: moved in by the same amount, usually four spaces. Indentation is not decoration in Python. It is how Python knows which lines are inside the if and which come after it.
# if statement program to check if a number is positivenumber = int(input("Enter a number: "))if number > 0: print("The number is positive.")Output
Enter a number: 25The number is positive.If the user types −4 instead, the condition is False and the program prints nothing at all.
The if-else statement
else adds the lines to run when the condition is false, so exactly one of the two blocks always runs.
if condition: # runs when the condition is Trueelse: # runs when the condition is False# Asking the user's age and giving a resultuser_age = int(input("How old are you? "))if user_age >= 18: print("You are an adult!")else: print("You are a teenager or a kid.")Output
How old are you? 15You are a teenager or a kid.The if-elif-else statement
When there are more than two possibilities, elif (short for “else if”) adds more conditions. Python checks them from the top, runs the block of the first condition that is true, and skips all the rest. else at the end catches whatever is left.
if condition1: # runs if condition1 is Trueelif condition2: # runs if condition1 is False and condition2 is Trueelse: # runs when condition1 and condition2 are both False# Is the number positive, negative or zero?user_number = int(input("Enter a number: "))if user_number > 0: print("The number is positive.")elif user_number == 0: print("The number is zero.")else: print("The number is negative.")Output
Enter a number: 0The number is zero.Nested if
A nested if is an if statement inside another if. The inner one is checked only when the outer condition is true.
if condition1: # runs if condition1 is True if condition2: # runs if condition1 and condition2 are both True else: # runs if condition1 is True but condition2 is Falseelse: # runs when condition1 is FalseIn Nepal you can get a citizenship certificate at 16 and vote at 18:
age = int(input("Enter your age: "))if age >= 16: print("You are eligible for citizenship.") if age >= 18: print("You are eligible to vote.") else: print("You are not eligible to vote yet.")else: print("You are a minor.")Output
Enter your age: 17You are eligible for citizenship.You are not eligible to vote yet.Look at the indentation: the inner if and its else are moved in one more step, so they belong to the outer if.
This program uses if, elif, else and an if inside an if: it says whether a number is positive, negative or zero, and whether a positive number is even or odd.
n = int(input("Enter a number: "))if n > 0: print("Positive") if n % 2 == 0: print("Even") else: print("Odd")elif n < 0: print("Negative")else: print("Zero")Here is the same program as a flowchart.
In the program above, the user types −3. Which lines does the program print?
Pick an answer to see why.
Iteration: loops
Iteration means doing something again and again. A loop repeats a block of lines, either a set number of times or until a condition stops being true. Python has two loops, for and while.
The for loop
A for loop goes through a sequence of values one at a time, running its block once for each. Use it when you know how many times to repeat.
for item in sequence: # lines to run for each itemThe sequence is often made by range():
range(…) |
gives | |
|---|---|---|
range(5) |
0, 1, 2, 3, 4 | starts at 0 and stops before 5: five numbers |
range(1, 11) |
1, 2, 3, … 10 | from 1, stopping before 11 |
range(2, 21, 2) |
2, 4, 6, … 20 | from 2, in steps of 2 |
range(10, 0, -1) |
10, 9, 8, … 1 | counting down |
# Using a for loop to print "Programming" five timesfor x in range(5): print("Programming")Output
ProgrammingProgrammingProgrammingProgrammingProgrammingThe variable x takes the values 0, 1, 2, 3 and 4 in turn; this program doesn’t use it, it only needs the five turns. A for loop can also go through the letters of a string or the items of a list: for letter in "Nepal": runs five times.
The while loop
A while loop repeats its block as long as its condition is true. It checks the condition before every round; when the condition is false, the loop ends and the program goes on after it.
while condition: # lines to repeat while the condition is True# Using a while loop to print the numbers from 1 to 5count = 1while count <= 5: print(count) count += 1Output
12345for loop |
while loop |
|
|---|---|---|
| Use it when | you know how many times to repeat, or have a sequence to go through | you repeat until something happens |
| It stops when | the sequence runs out | its condition becomes false |
| Example | print the 5 times table, 1 to 10 | keep asking for a password until it is right |
How many times does for i in range(3, 8): repeat?
Pick an answer to see why.
Python lists
A list stores many values in a single variable, in order, inside square brackets and separated by commas. The values can be of different types.
thislist = ["Computer", "Science", 20, True]print(thislist)print(thislist[0])print(len(thislist))Output
['Computer', 'Science', 20, True]Computer4Each item has a position number, its index, starting from 0: thislist[0] is "Computer", thislist[1] is "Science". Counting from the end, thislist[-1] is the last item, True. len() gives the number of items, and append() adds a new one at the end:
marks = [72, 85, 64]marks.append(90)print(marks, sum(marks), max(marks))Output
[72, 85, 64, 90] 311 90Exercise: the basics of Python
1. Choose the correct answer
i. Which statement is used to display output in Python?
Pick an answer to see why.
ii. Which of the following is not a Python data type?
Pick an answer to see why.
iii. What type of values does the Boolean data type hold?
Pick an answer to see why.
iv. Which of the following is a relational operator?
Pick an answer to see why.
v. Which logical operator returns True only if both conditions are true?
Pick an answer to see why.
vi. What is the purpose of the if statement in Python?
Pick an answer to see why.
vii. Which conditional statement lets you check several conditions one after another?
Pick an answer to see why.
viii. What is the term for repeating a block of code several times?
Pick an answer to see why.
ix. Which loop is used when you know how many times you want to repeat a block of code?
Pick an answer to see why.
x. Which data structure stores several items in one variable, as in ["Computer", "Science", 20, True]?
Pick an answer to see why.
2. Write short answers to these questions
What is the main job of the input() function in Python?
Answer
Give an example of a string literal in Python.
Answer
What is an identifier in Python programming?
Answer
Explain the difference between the division operator (/) and the floor division operator (//).
Answer
Define the concept of data types in Python.
Answer
What is the purpose of relational operators in Python? Give one example.
Answer
Describe what the else block does in an if-else statement.
Answer
What is a nested if statement?
Answer
When would you use a for loop instead of a while loop?
Answer
What does the range() function do in for loops?
Answer
Define a Python list and give a simple example.
Answer
Discuss the concept of iteration in programming.
Answer
3. Write long answers to these questions
Explain the categories of operators in Python (arithmetic, relational and logical), with examples of each.
Answer
Describe the three main types of conditional statements in Python (if, if-else and if-elif-else).
Answer
Explain Python’s two loops, for and while, with their syntax and a practical example of each.
Answer
Describe the four basic data types (integer, float, string and Boolean), with an example of each. Why is it important to understand data types when writing Python programs?
Answer
Write a Python program that takes an integer from the user and: prints “Positive” if the number is greater than 0, “Negative” if it is less than 0, and “Zero” if it is 0; and if the number is positive, also checks whether it is even or odd and prints the result. Your program should show input and output, conditional statements (including a nested if) and arithmetic operators.
Hint
Answer
4.2 User-defined functions
Suppose a program has to work out the area of a rectangle in ten different places. You could write length * width ten times, but if you later find a mistake, you have to fix it ten times. A better way is to write the instructions once, give them a name, and use the name whenever you need them. That named block is a function.
A function is a block of organized, reusable code that does one particular job. It runs only when it is called (used) by its name. Functions make a program modular: split into small parts, each easy to read, test and fix, and each usable again and again.
Types of functions
- Built-in functions come with Python and are always ready to use, because they are loaded as soon as the Python interpreter starts:
print(),input(),int(),len(),sum(),max(),type()and many more. - User-defined functions are the functions we write ourselves, for the jobs our own program needs.
There are also functions that live in modules, such as math.sqrt(): they come with Python but must be imported first (section 4.3).
Creating a user-defined function
A function definition begins with the keyword def (short for “define”):
def function_name(parameter1, parameter2, ...): statements to run return value- The first line, the function header, has
def, the function’s name, its parameters in brackets, and always ends with a colon (:). - The parameters are optional: a function may have none, but the brackets are still needed:
def greet():. - The function’s name follows the rules for identifiers, and should be different from every other name in the program.
- The body is every line indented under the header. The first line that is not indented is no longer part of the function.
returnis optional too: a function may or may not send a value back.
def, the name, the parameters and the indented body, and a call with its arguments. The call jumps into the function; return jumps back with the answer. Defining a function does not run it. Python only remembers it. The lines inside run each time the function is called, by writing its name with values in brackets:
# Program to show the use of a user-defined functiondef add_numbers(x, y): total = x + y return total num1 = 5num2 = 6print("The sum is", add_numbers(num1, num2))Output
The sum is 11Python reads lines 2 to 4 and remembers the function, but runs nothing in it. The program really starts on line 6. On line 8, the call add_numbers(num1, num2) sends 5 and 6 into the function, which adds them and returns 11; print then shows it.
A function that returns a value
return sends a value back to the line that called the function, and the call is replaced by that value, as if you had written the value there. The function can do its work with its own inputs and give back the result:
# Function to calculate the area of a rectangledef area(length, width): return length * width l = 5w = 8result = area(l, w)print("Area of the rectangle:", result)Output
Area of the rectangle: 40As soon as Python reaches return, the function ends: any lines under it in the function are never run.
Parameters and arguments
Parameters are the names in brackets in the function header: they are the values the function needs to do its job. Arguments are the actual values given in brackets when the function is called. When the function is called, each argument is put into its parameter, in order.
# Function to calculate the area of a circledef area_of_circle(radius): area = radius ** 2 * 22 / 7 return area r = float(input("Enter the radius of the circle: "))print("The area of the circle is", area_of_circle(r))Output
Enter the radius of the circle: 7The area of the circle is 154.0Here radius is the parameter and r (holding 7.0) is the argument. An argument can be a constant (area_of_circle(7)), a variable (area_of_circle(r)) or an expression (area_of_circle(d / 2)). Arguments must be given in the same order as the parameters are listed.
| Parameter | Argument | |
|---|---|---|
| Where | in the function header, in def |
in the function call |
| What it is | a name, waiting for a value | the value that is sent |
| Example | radius in def area_of_circle(radius): |
7 in area_of_circle(7) |
Scope of a variable
The scope of a variable is the part of the program where it can be used.
- Local scope. A variable made inside a function (including its parameters) is local to that function: it exists only while the function runs and can be used only inside it. Once the function returns, its local variables are gone.
- Global scope. A variable made outside every function, in the main program, is global: it can be read anywhere in the program, inside functions too.
number = 10 # global variable def add_five(): result = number + 5 # result is local print("Inside the function:", result) add_five()print("Outside:", number)print(result) # error: result is local to add_fiveOutput
Inside the function: 15Outside: 10Error message
Traceback (most recent call last): File "scope.py", line 9, in <module> print(result) # error: result is local to add_five ^^^^^^NameError: name 'result' is not definednumber, but the main program can’t see the local result. Functions follow the same rule: a function defined at the top level of a program (not inside another function) can be called from anywhere in that program after its definition.
Passing parameters
A function call must give the function every value it needs: if the header has three parameters, the call normally sends three values. Python has three ways of matching arguments to parameters.
1. Positional (required) arguments
The arguments are matched to the parameters by position: the first argument to the first parameter, the second to the second, and so on. Their number must match.
def check(a, b, c): print(a, b, c) check(x, y, z) # 3 values, all variablescheck(2, x, y) # 3 values: a literal and two variablescheck(2, 5, 7) # 3 values, all literalscheck(2, 5) would be an error: TypeError: check() missing 1 required positional argument: 'c'.
2. Default arguments
Sometimes a parameter nearly always has the same value. A bank’s interest rate might be 10% for most accounts. A default value, written in the header like an assignment, is used whenever the call doesn’t give that argument:
def interest(prin, time, rate=0.10): return prin * time * rate print(interest(2000, 2)) # rate is the default, 0.10print(interest(2000, 2, 0.12)) # rate given, 0.12Output
400.0480.0The rule: once a parameter has a default, every parameter after it must have one too. Python matches arguments from the left, so a required parameter can’t come after an optional one.
| Function header | |
|---|---|
def interest(prin, time, rate=0.10): |
legal |
def interest(prin, time=2, rate=0.10): |
legal |
def interest(prin=2000, time=2, rate=0.10): |
legal |
def interest(prin, time=2, rate): |
illegal: a default parameter before a required one |
def interest(prin=2000, time=2, rate): |
illegal: the same mistake |
3. Keyword (named) arguments
Defaults let you leave out an argument, but you still have to remember the order. With keyword arguments, you name each argument in the call, name=value, and then the order doesn’t matter:
print(interest(prin=2000, time=2, rate=0.10))print(interest(time=4, prin=2600)) # rate is the defaultprint(interest(time=2, rate=0.12, prin=2000))Output
400.01040.0480.0All three calls are valid, although the order of the arguments doesn’t match the order of the parameters in the header. Positional and keyword arguments can be mixed, as in interest(2600, rate=0.09, time=2), but the positional ones must come first.
Returning values from functions
Functions in Python may or may not return a value, so there are two kinds.
1. Functions that return a value (non-void functions)
These work out a result and send it back with return value. The value can be a literal (return 0), a variable (return total) or an expression (return x + y).
def add(x, y): return x + y result = add(5, 3) # the call is replaced by the returned 82. Functions that don’t return a value (void functions)
These do something, such as print a message or draw a shape, but give no answer back. A void function either has no return or a return with nothing after it, which simply ends the function.
def greet(): print("Hello") def quote(): print("Python is good") return def greet_by_name(name): print("Hello", name) def print_sum(a, b, c): print("Sum is", a + b + c) returnA void function still gives something back: Python’s special empty value, None.
def greet(): print("Hello") x = greet()print(x)Output
HelloNoneLine 4 calls greet(), which prints Hello. It returns nothing, so x gets None, and line 5 prints that.
Returning several values
A function can send back several values at once: list them after return, separated by commas.
return value1, value2, value3Python packs them into a tuple, a list-like sequence written in round brackets:
def squared(x, y, z): return x * x, y * y, z * z t = squared(2, 5, 7)print(t)Output
(4, 25, 49)The caller can also unpack the values straight into separate variables, one for each:
def squared(x, y, z): return x * x, y * y, z * z v1, v2, v3 = squared(2, 3, 4)print("The returned values are:")print(v1, v2, v3)Output
The returned values are:4 9 16Exercise: user-defined functions
1. Choose the correct answer
i. Which keyword is used to define a user-defined function in Python?
Pick an answer to see why.
ii. What are the values passed to a function when it is called known as?
Pick an answer to see why.
iii. The part of the program where a variable or function can be accessed is called its:
Pick an answer to see why.
iv. Variables declared inside a function have:
Pick an answer to see why.
v. What does the return statement do in a Python function?
Pick an answer to see why.
vi. What are the names written within the brackets of the function header called?
Pick an answer to see why.
vii. What type of argument lets you call a function by naming the parameters?
Pick an answer to see why.
viii. A function that performs an action but does not return a value is called a:
Pick an answer to see why.
ix. Can a Python function return multiple values?
Pick an answer to see why.
2. Write short answers to these questions
What is the main benefit of using user-defined functions in programming?
Answer
Name the two types of Python functions.
Answer
Explain the difference between a parameter and an argument in a Python function.
Answer
What is local scope in Python functions? Give a brief example.
Answer
What is global scope in Python? How does it differ from local scope?
Answer
What is the purpose of the return keyword in a Python function?
Answer
Explain what positional arguments are and how they are passed to a function.
Answer
Describe the use of default arguments in Python functions.
Answer
What are keyword arguments, and what advantage do they offer when calling a function?
Answer
What happens if a void function has a return statement without any value?
Answer
3. Write long answers to these questions
Explain the concept of function scope in Python, differentiating between local and global scope.
Answer
Describe the concept of return values in Python functions. Differentiate between functions that return a value (non-void) and those that do not (void). Give examples of both, and explain how the return value can be used in the calling part of the program.
Answer
Python allows functions to return multiple values. Explain how this is done, with an example of a function that returns several values and how the caller can use them.
Answer
Design a Python program with at least two user-defined functions: one that takes two numbers as arguments and returns their product, and another that takes a list of numbers as an argument and prints each number.
Answer
4.3 Libraries and packages in Python
Nobody writes every program from nothing. Programmers around the world have already written, tested and shared code for square roots, random numbers, tables of data, charts and much more. Python lets you use it with one line: import.
import: modules from the standard library come with Python; packages such as matplotlib and pandas are installed first with pip. - A module is one file of Python code (a
.pyfile) holding functions and values for one area, such asmathorrandom. - A package is a folder of related modules, used with a dot:
matplotlib.pyplotis the modulepyplotin the packagematplotlib. Packages keep large collections of code organized and reusable. - A library is a collection of modules and packages that together meet one kind of need. NumPy is a library for scientific computing, with large arrays of numbers and many maths functions; Pandas works with tables of data; Matplotlib draws charts, often of data from Pandas.
Python comes with a large standard library, already installed: math, random, csv, turtle, datetime and hundreds more. Other libraries, such as Pandas and Matplotlib, are installed separately with pip, Python’s installer, from the command prompt or terminal: pip install pandas.
4.3.1 Importing and using standard libraries
To use a module, import it at the top of the program. Several can be imported in one line:
import math, randomThere are four ways to import, depending on how you want to write the names afterwards:
a. Import the whole module. Then use module_name.function_name():
import mathprint(math.sqrt(25))Output
5.0b. Import one function from it. Then use the function’s name alone, without math. in front:
from math import sqrtprint(sqrt(25))Output
5.0c. Import a module with an alias (a short name of your own):
import datetime as dtprint(dt.datetime.now()) # today's date and the time nowOutput
2026-10-18 10:42:07.351862dt is now short for datetime. (The time printed is whenever you run it.) This is how Pandas and Matplotlib are almost always imported: import pandas as pd.
d. Import everything from a module:
from math import *print(sin(90))Output
0.8939966636005579Which of these is not part of Python’s standard library, and has to be installed with pip?
Pick an answer to see why.
4.3.2 Popular libraries: Math, Random, Pandas, Turtle and Matplotlib
1. Math
math is a standard module with mathematical functions and constants beyond Python’s operators:
| What | Examples |
|---|---|
| constants | math.pi (3.14159…), math.e (2.71828…) |
| roots and powers | math.sqrt(256) is 16.0; math.pow(2, 10) is 1024.0 |
| trigonometry (radians) | math.sin(), math.cos(), math.tan(), math.radians() |
| logarithms | math.log10(1000) is 3.0; math.log() |
| rounding | math.ceil(4.2) is 5 (up); math.floor(4.8) is 4 (down) |
| others | math.factorial(5) is 120 |
import mathx = math.sqrt(256)print("Square root is", math.sqrt(16))print("Value is", math.sin(math.pi / 2))print("x is equal to", x)Output
Square root is 4.0Value is 1.0x is equal to 16.0math.sqrt() always gives a float, so 16.0, not 16. math.pi / 2 radians is 90°, whose sine is 1.
2. Random
random makes random numbers and random choices: for games, simulations, drawing lots or making test data.
| Function | Gives |
|---|---|
random.randint(a, b) |
a random whole number from a to b, both included |
random.randrange(a, b) |
a random whole number from a up to b, b not included (like range) |
random.choice(seq) |
a random item from a list, tuple or string |
random.random() |
a random float from 0.0 up to (not including) 1.0 |
import randomprint(random.randint(1, 10))print(random.choice(['apple', 'banana', 'orange']))r1 = random.randint(5, 15)print("Random number between 5 and 15 is", r1)r2 = random.randint(-10, -2)print("Random number between -10 and -2 is", r2)Output
7bananaRandom number between 5 and 15 is 12Random number between -10 and -2 is -6This is only one possible output: run it again and you get different numbers.
3. Pandas
Pandas is a library for working with large tables of data: reading them from files (CSV, Excel, databases), sorting and filtering them, filling in missing values, and summing or averaging them. Its main data structure is the DataFrame, a table with named columns and numbered rows, like a sheet in a spreadsheet. Pandas is not part of Python, so install it first: pip install pandas. If it isn’t installed, import pandas fails with ModuleNotFoundError: No module named 'pandas'.
| Pandas function | What it does |
|---|---|
pandas.DataFrame() |
makes a table (DataFrame) from data, such as a dictionary of columns |
pandas.read_csv() |
loads a CSV file into a DataFrame |
DataFrame.info() |
summarizes a DataFrame: its column names, data types and missing values |
DataFrame.shape |
the size of the table as (rows, columns) |
import pandas as pddata = {'Name': ['Shyam', 'Sanskar'], 'Age': [25, 30]}df = pd.DataFrame(data)print(df)Output
Name Age0 Shyam 251 Sanskar 30The { } on line 2 is a dictionary: each column’s name ('Name', 'Age') with the list of its values. Pandas numbers the rows from 0 on the left; these numbers are the DataFrame’s index. You will use Pandas with files in section 4.6.
4. Turtle
turtle is a standard module for drawing. It opens a window with a small pointer, the turtle, that draws a line wherever it moves, like a pen on paper. Its methods:
| Method | What it does |
|---|---|
forward(n) |
moves the turtle forward n steps |
backward(n) |
moves it backward n steps |
right(angle) |
turns it clockwise by the angle, in degrees |
left(angle) |
turns it anticlockwise |
goto(x, y) |
moves it to the point (x, y) |
pendown() |
puts the pen down, so it draws when it moves |
penup() |
lifts the pen, so it moves without drawing |
Turtle() |
makes and returns a new turtle |
done(), mainloop() |
keep the window open, waiting for the user |
import turtles = turtle.Turtle()for i in range(4): s.forward(50) s.right(90)turtle.done()5. Matplotlib
Matplotlib is a library for drawing graphs and charts of high quality, created by John D. Hunter in 2003. It is free and open source. It can draw line plots, scatter plots, bar charts, pie charts, histograms, box plots and even 3-dimensional plots. Install it with pip install matplotlib. Most programs use its pyplot module, imported as plt. Three common kinds of chart:
- A line plot shows how one quantity changes with another, usually over time, with the points joined by lines.
- A bar chart compares values for separate categories (a number for each class, each day, each district) as bars.
- A pie chart shows how a whole is divided into parts, each slice’s share of the circle being its share of the total.
import matplotlib.pyplot as pltdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri']plates = [40, 55, 48, 62, 70, 85]plt.plot(days, plates)plt.title('Momos sold this week')plt.xlabel('Day')plt.ylabel('Plates')plt.show()plt.plot(x, y) draws a line through the points; plt.show() opens the chart in a window. You will make every kind of chart in section 4.7, and can try them in the chart maker there.
4.4 Graphics using Turtle
The turtle module is a ready-made module of Python’s standard library for drawing pictures, shapes and designs in a window, with a pointer called the turtle. These are its most important methods:
| Method | Parameter | What it does |
|---|---|---|
forward() |
distance | moves the turtle forward by the distance |
backward() |
distance | moves it backward by the distance |
right() |
angle | turns it clockwise |
left() |
angle | turns it anticlockwise |
penup() |
none | lifts the pen: it moves without drawing |
pendown() |
none | puts the pen down again |
color() |
color name | changes the color of the pen (and of the fill) |
fillcolor() |
color name | changes the color used to fill a shape |
shape() |
shape name | changes how the turtle itself looks |
Why learn with Turtle?
- You see the concepts. Loops, functions and variables become shapes and patterns you can watch being drawn.
- It is interactive. You command the turtle where to go and what to draw, and see the result at once.
- It builds creativity. A beginner can make striking patterns with a few lines of code.
- Mistakes are easy to find. If the drawing is wrong, you can see where it went wrong, and Python is easier to read and correct than older graphics languages such as C graphics.
Where the turtle starts
left(30) turns it to heading 30; right(30) turns it to heading 330 (the same as −30). The turtle starts in the middle of the window, at the point (0, 0), facing right (east), with its pen down. Its heading, the direction it faces, is measured in degrees anticlockwise from east: 0 is east, 90 is north (up), 180 west and 270 south. left() adds to the heading and right() takes away from it.
Turtle motion
a. forward(distance), or fd(distance), moves the turtle forward, in the direction it faces, by the distance in steps (pixels). The distance can be an integer or a float.
import turtlesk = turtle.Turtle()sk.forward(50)turtle.done()b. backward(distance), or back() or bk(), moves the turtle in the opposite direction to the one it faces, without turning it round.
import turtlesk = turtle.Turtle()sk.backward(50)turtle.mainloop()c. right(angle), or rt(angle), turns the turtle clockwise by the angle, in degrees. It only turns: it doesn’t move. heading() gives the direction the turtle faces now.
import turtlet = turtle.Turtle()print(t.heading())t.right(30)print(t.heading())turtle.mainloop()Output
0.0330.0The turtle starts facing east, heading 0. Turning right (clockwise) by 30° takes it to 330°, since headings are measured anticlockwise.
d. left(angle), or lt(angle), turns the turtle anticlockwise by the angle.
import turtlet = turtle.Turtle()print(t.heading())t.left(100)print(t.heading())turtle.mainloop()Output
0.0100.0The pen and colors
penup() lifts the turtle’s pen off the canvas: the turtle can then move without drawing. pendown() puts it down again. Lifting and lowering the pen in a loop draws a dashed line:
import turtleturtle.color("red")turtle.hideturtle()turtle.speed(1)turtle.left(90)for i in range(4): turtle.forward(30) turtle.penup() turtle.forward(30) turtle.pendown()turtle.exitonclick()hideturtle() hid the turtle itself. The functions can also be called on the module itself, as turtle.forward(30), without making a Turtle() first: Python then uses one turtle of its own. speed(1) makes it draw slowly enough to watch (from 1, slowest, to 10; 0 means no animation), and exitonclick() keeps the window open until it is clicked.
color() changes the color of the turtle’s pen, from then on. The color starts as black. It takes a color name in quotes, such as "blue", or a hex code such as "#1e90ff".
import turtleturtle.forward(50)turtle.color("blue") # change the colour of the penturtle.forward(150)turtle.color("red")turtle.forward(50)fillcolor() chooses the color for filling a closed shape. Two more methods go with it: begin_fill(), just before drawing the shape, and end_fill() just after it, which fills the shape drawn in between.
import turtlet = turtle.Turtle()r = int(input("Enter the radius of the circle: "))col = input("Enter a colour name or hex value (#RRGGBB): ")t.fillcolor(col) # set the fill colourt.begin_fill() # start fillingt.circle(r) # draw a circle of radius rt.end_fill() # fill itturtle.done()Output
Enter the radius of the circle: 50Enter a colour name or hex value (#RRGGBB): orangecircle(r) draws a circle with its center r steps to the turtle’s left, so it lies above the start. Python’s turtle knows the spelling color only: turtle.colour("red") gives an AttributeError. Color names are in American spelling too, such as "gray".
The turtle’s shape
shape(name) changes how the turtle itself looks. Its shapes are "arrow", "turtle", "circle", "square", "triangle" and "classic" (the default). Called with no name, shape() gives the name of the current shape.
import turtleturtle.forward(100) # the default shape, "classic"turtle.shape("circle")turtle.right(60)turtle.forward(100)turtle.shape("triangle")turtle.right(60)turtle.forward(100)turtle.shape("square")turtle.right(60)turtle.forward(100)turtle.shape("arrow")turtle.right(60)turtle.forward(100)turtle.shape("turtle")turtle.right(60)turtle.forward(100)The program below repeats “forward, then turn” as many times as you choose. Which settings close the shape? Try 5 repeats of 144°.
4.5 Error handling: errors, exceptions and try-except
Every programmer makes mistakes, beginners and experts alike. No matter how carefully a program is planned, something will sometimes go wrong: a missing colon, a user who types “ten” instead of 10, a file that has been deleted. Error handling is how a programmer finds these problems, deals with them, and keeps a program working, so that it is robust: it doesn’t crash on unexpected input, and it is easier to look after.
Errors and exceptions
An error is a problem in a program that stops it from working, or from working correctly. There are three kinds.
i. Syntax errors
A syntax error is a mistake in the rules of how Python must be written (its syntax), such as a missing colon, a missing bracket or quote, or wrong indentation. Python checks the whole program before running it, so a syntax error stops the program before a single line runs.
marks = 75if marks >= 35 print("Pass")Error message
File "result.py", line 2 if marks >= 35 ^SyntaxError: expected ':'Python names the file and the line, points with ^ at where it noticed the problem, and says what it expected: the colon at the end of line 2.
ii. Runtime errors
A runtime error happens while the program is running, after Python has accepted its syntax: a line that is written correctly turns out to be impossible to carry out, such as dividing by zero.
numerator = int(input("Enter numerator: "))denominator = int(input("Enter denominator: "))result = numerator / denominatorprint(f"Result: {result}")Output
Enter numerator: 10Enter denominator: 0Error message
Traceback (most recent call last): File "divide.py", line 3, in <module> result = numerator / denominator ~~~~~~~~~~^~~~~~~~~~~~~ZeroDivisionError: division by zeroWith 10 and 4 the same program works perfectly and prints Result: 2.5. The error depends on the data, which is why runtime errors are harder to find than syntax errors.
The f before the string in line 4 makes it an f-string: Python replaces {result} with the value of result.
iii. Logical errors
A logical error is a mistake in the program’s logic: it runs without any error message, but gives the wrong answer. Python can’t catch it, because to Python nothing is wrong. Only testing, by checking the output against answers you know, finds it.
first = int(input("Enter the first number: "))second = int(input("Enter the second number: "))average = first + second / 2print("The average is", average)Output
Enter the first number: 8Enter the second number: 6The average is 11.0The average of 8 and 6 is 7, not 11. Since / is worked out before +, line 3 calculates 8 + (6 / 2) = 11. The correct line is average = (first + second) / 2. Forgetting the f of an f-string is another common logical error: print("The average is {average}") prints the words {average} themselves.
iv. Exceptions
Even when a line is written correctly, it may cause an error when Python tries to run it. An error detected while the program runs is called an exception. Python raises an exception, and, unless the program handles it, stops and shows an error message. A program can catch the exceptions it expects and deal with them. For example, this line is correct Python, but raises a ZeroDivisionError when it runs:
divide_by_zero = 7 / 0Reading an error message
When a program stops with an error, Python prints a traceback. Read it from the bottom up: the last line gives the error’s type and what went wrong; the lines above say in which file and on which line it happened.
| Error | What it means | Example that causes it |
|---|---|---|
SyntaxError |
the code breaks Python’s rules of writing | if x > 5 (no colon); a missing bracket or quote |
IndentationError |
the indentation is wrong | a line under def or if that isn’t moved in |
NameError |
a name is used that doesn’t exist (yet) | a misspelled name, prnt("hi"); a variable used before it is given a value |
TypeError |
an operation on the wrong type of value | "Age: " + 15 (text and a number) |
ValueError |
the right type, but a value that doesn’t fit | int("abc") |
ZeroDivisionError |
dividing by zero | 7 / 0, 7 % 0 |
IndexError |
a list position that doesn’t exist | marks[5] when the list has 3 items |
ModuleNotFoundError |
importing a module that isn’t installed, or is misspelled | import pandaz |
FileNotFoundError |
opening a file that isn’t there to read | open("missing.txt") |
AttributeError |
a method or value the thing doesn’t have | turtle.colour("red") (it is color) |
Python’s messages often help more than you expect: NameError: name 'prnt' is not defined. Did you mean: 'print'?
A program runs without any error message, but prints that the average of 8 and 6 is 11. What kind of error is this?
Pick an answer to see why.
Exception handling: try, except, else and finally
Normally an exception stops the program and shows an error message: fine for the programmer, but not for someone using the program. To make a program reliable, a programmer expects the errors that can happen and says what to do instead: show a helpful message, ask again, or use a sensible value. This is exception handling, done with four blocks:
tryblock: the code that might cause an error. Python tries to run it. If an exception happens, Python leaves thetryblock at once, skipping the rest of it, and jumps to the matchingexceptblock.exceptblock: handles the error. It runs only if its exception happened in thetryblock.except ValueError:handles only aValueError; a program can have severalexceptblocks, one for each error, and a plainexcept:catches every exception.elseblock (optional): comes after all theexceptblocks and runs only if no exception happened in thetryblock. It holds what should happen when everything went well.finallyblock (optional): runs every time, whether there was an exception or not. It is used for cleaning up, such as closing a file.
try block raises an error, the matching except runs; if not, the else runs. The finally block runs either way. try: n = int(input("Number: ")) r = 100 / nexcept ValueError: print("Not a whole number.")except ZeroDivisionError: print("Can't divide by zero!")else: print("100 /", n, "=", r)finally: print("Done.")Output
Number: abcNot a whole number.Done.Which lines run when the user types 4, or 0, or abc? Choose what the user types below, then step through with Next line.
Exercise: libraries, packages and errors
1. Choose the correct answer
i. A collection of modules that together meet a particular need, such as data analysis, is called a:
Pick an answer to see why.
ii. Which of the following is a popular Python library used for data manipulation and analysis?
Pick an answer to see why.
iii. In Python, what is a folder of modules, used with a dot as in matplotlib.pyplot, called?
Pick an answer to see why.
iv. Which statement is used to access modules from a Python package?
Pick an answer to see why.
v. Which of the following is a correct way to import in Python?
Pick an answer to see why.
vi. Which Python module provides functions for generating random numbers?
Pick an answer to see why.
vii. What type of error occurs when the code breaks the rules of the programming language’s syntax?
Pick an answer to see why.
viii. Errors detected during the execution of a program are called:
Pick an answer to see why.
ix. Which block is used to test a block of code for errors in Python?
Pick an answer to see why.
x. Which block in error handling always runs, whether an exception occurred or not?
Pick an answer to see why.
2. Write short answers to these questions
Define the term “module” in Python programming.
Answer
What is the relationship between modules and libraries in Python?
Answer
Give an example of a built-in Python library and its purpose.
Answer
Explain why packages are useful for code organization and reusability.
Answer
What is the purpose of using an alias when importing a module in Python? Give an example.
Answer
Name two functions provided by Python’s math module.
Answer
What is a runtime error? Give an example of a situation that might cause one.
Answer
Explain the difference between an error and an exception in Python.
Answer
What is the role of the except block in a try-except statement?
Answer
When is the else block in a try-except-else statement executed?
Answer
3. Write long answers to these questions
Explain the concepts of Python libraries and packages, and why they are important in software development.
Answer
Introduce three popular Python libraries: Pandas, Turtle and Matplotlib. For each, describe its main purpose and give a simple example of how it is used.
Answer
Discuss the types of error that can occur in Python programs: syntax errors, runtime errors and logical errors. Give an example of each, and explain how each affects the running and the correctness of a program.
Answer
Explain the importance of error handling in Python.
Answer
Sample programs
Each program solves a common task, the kind SEE asks you to write. Try writing it yourself before you open the program.
4.6 File handling, and CSV files with Pandas
Everything a program keeps in its variables is lost the moment it ends, or the computer is switched off. To keep data for later, a program saves it in a file: a collection of data stored on a disk as one unit, with a file name. Python’s built-in functions create, open, read, write and close files, and the Pandas library makes it easy to read and write files of data, such as CSV and Excel files.
4.6.1 File handling in Python
File handling means a program working with files on the computer: creating them, reading data from them, writing or adding data to them, renaming and deleting them.
Why file handling is useful:
- Data is kept: results, records and settings survive after the program ends, for the next run or for another program.
- It is versatile: Python can create, read, write, append to, rename and delete files.
- It is flexible: it works with many kinds of file: text files, CSV files, binary files such as pictures, and (with Pandas) Excel and JSON.
- It is easy to use: a few lines open, read and close a file.
- It works on every platform: the same Python code works on Windows, macOS and Linux.
What can go wrong:
- Errors: the file may not exist, the program may not be allowed to open it, or another program may be using it; careless code then crashes (with
tryandexceptit needn’t). - Security risks: a program that lets a user type any file name could be used to read or change files it shouldn’t.
- Lost data: opening a file in the wrong mode can wipe it in an instant (below).
- Speed: reading from and writing to a disk is much slower than working in memory, which shows with very large files.
4.6.2 File modes: read, write and append
The first step for any work on a file is to open it, with Python’s built-in open() function. It takes the file name and a mode, which says what you are going to do with the file, and gives back a file object to work with:
file = open("notes.txt", "r")| Mode | Name | What it does | If the file doesn’t exist | If the file exists |
|---|---|---|---|---|
"r" |
read | read only; you can’t change the file (the default mode) | error: FileNotFoundError |
read from its start |
"w" |
write | write only; you can’t read | creates it | wipes everything in it, then writes |
"a" |
append | write only, adding to the end | creates it | keeps what is there and adds to the end |
"x" |
create | make a new file and write to it | creates it | error: FileExistsError |
Adding + to a mode lets the file be both read and written: "r+", "w+" and "a+" (with the same rules about wiping and creating as the mode without the +).
The program below opens notes.txt in the mode you choose, then reads it or writes Hari,10 into it. What happens to Sita and Ram’s lines in "w"? What happens if you delete the file and try "r"?
Reading a file
To read a file, open it in read mode. A file object has three methods for reading:
read()reads the whole file, from where it has reached to the end, as one string;read(n)reads the next n characters;readline()reads the next line;readlines()reads all the lines, as a list of strings.
The file nl.txt holds three lines:
nl.txt
Namaste from NepalPython is funFiles keep datanl = open("nl.txt", "r") # open the file in read modeprint(nl.readline()) # read the first lineprint(nl.read(10)) # read the next 10 charactersprint(nl.read()) # read the restnl.close()Output
Namaste from Nepal Python is funFiles keep dataThe file object remembers how far it has read, like a bookmark. After readline() has read the first line, read(10) reads the next 10 characters, Python is (with its space), not the first 10 of the file; and read() reads only what is left. (The empty lines appear because each line read from the file ends with a new-line character, \n, and print() adds another.)
Closing a file
When you have finished with a file, close it with close(). Closing saves everything written to the disk and frees the file for other programs; a file left open can lose its last writes if the program crashes. It is good practice to always close a file:
nl = open("nl.txt", "r")print(nl.read())nl.close()Python can close the file for you. Open it with with, and Python closes the file automatically when the indented block ends, even if an error happens inside it:
with open("nl.txt", "r") as nl: print(nl.read())# here the file is already closedCreating a file
Two modes create a new file:
"x"creates a new, empty file, but raises an error if a file with that name already exists, so it can never wipe an existing file;"w"creates the file if it doesn’t exist, and if it does, wipes it without any warning.
nl = open("nl.txt", "x") # a new empty file; FileExistsError if nl.txt existsnl = open("nl.txt", "w") # a new file; if nl.txt exists, it is emptiedWriting to a file
write() writes a string into the file. In "w" mode the file is emptied first, and if it doesn’t exist, it is made:
file = open("Test.txt", "w")file.write("Hello, World!")file.close()Nothing appears on the screen: the text goes into Test.txt. write() doesn’t start a new line by itself, so put \n, the new-line character, at the end of each line:
with open("file.txt", "w") as nl: nl.write("This is the first line\n") nl.write("This is the second line\n") nl.write("This is the third line\n")writelines() writes a whole list of strings in one go (again, without adding new lines of its own):
nl = open("file.txt", "w")nl.writelines(["This is the first line\n", "This is the second line\n", "This is the third line\n"])nl.close()To add to a file without losing what is already there, open it in append mode, "a":
file = open("file.txt", "a")file.write("Python programming is fun")file.close()file.txt
This is the first lineThis is the second lineThis is the third linePython programming is funA file marks.txt holds a whole class’s marks. A program runs f = open("marks.txt", "w"). What happens to the marks already in the file?
Pick an answer to see why.
4.6.3 Reading and writing CSV files
CSV (comma-separated values) is the most common format for moving tables of data between spreadsheets, databases and programs. A CSV file is plain text: each line is one record (a row), the values in it are separated by commas, and the first line usually gives the names of the columns:
result.csv
Name,Gender,ComputerAarati,F,92Bibek,M,88Chandra,M,74CSV files are popular because they are:
- portable: plain text, so any text editor or spreadsheet program (Excel, LibreOffice Calc, Google Sheets) can open and edit them;
- simple: their structure is so plain that programs can easily write and read them;
- widely supported: almost every programming language, including Python, can read and write them.
There are two main ways to read CSV files in Python: the csv module of the standard library, and the Pandas library.
a. With the csv module
The csv module comes with Python, so nothing needs installing. It copes with different separators and with values that contain commas inside quotes, and it reads and writes row by row, so it can handle very large files without filling the memory. To read a file, open it as a text file with open(), then pass the file object to csv.reader(), which splits each line into a list of values:
import csvwith open("result.csv", "r") as csvfile: # open the CSV file in read mode csv_reader = csv.reader(csvfile) # make a reader object for row in csv_reader: # go through the rows print(row)Output
['Name', 'Gender', 'Computer']['Aarati', 'F', '92']['Bibek', 'M', '88']['Chandra', 'M', '74']Every value comes out as a string, even the marks: '92', not 92. To calculate with them, convert them with int().
b. With the Pandas library
Pandas reads the whole file in one line, into a DataFrame, and works out for itself which columns hold numbers.
Step 1: Import the Pandas library:
import pandas as pdStep 2: Load the CSV file with read_csv():
df = pd.read_csv("result.csv")Its full form is pandas.read_csv(filename, sep=","); sep (or its other name, delimiter) gives the character between the values, and is a comma unless you say otherwise: sep=";" for a file that uses semicolons.
pd.read_csv() turns the lines of a CSV file into a DataFrame: the first line gives the column names, each line after it becomes a row, and Pandas numbers the rows 0, 1, 2… (the index). Step 3: Get the column (field) names with .columns:
print(df.columns)Output
Index(['Name', 'Gender', 'Computer'], dtype='str')(Versions of Pandas before 3.0 show dtype='object' here: both mean the names are text.)
Step 4: Get the data of one column by its name, df['Computer'] (or df.Computer, when the name has no spaces):
print(df['Computer'])print("Average:", df['Computer'].mean())Output
0 921 882 74Name: Computer, dtype: int64Average: 84.66666666666667And the whole table:
import pandas as pddf = pd.read_csv("result.csv") # read the CSV fileprint(df) # show its contentsOutput
Name Gender Computer0 Aarati F 921 Bibek M 882 Chandra M 74A few more things you can do with a DataFrame:
| Code | Gives |
|---|---|
df.head(), df.head(3) |
the first 5 rows, or the first 3 |
df.shape |
the size, as (rows, columns): (3, 3) |
df.info() |
a summary: the columns, their data types, and missing values |
df['Computer'].mean(), .max(), .min(), .sum() |
the average, highest, lowest and total of a column |
df[df['Computer'] >= 80] |
only the rows where the condition is true |
The last one is called filtering. df['Computer'] >= 80 gives a True or False for every row, and df[…] keeps only the rows that are True. Two conditions are joined with & (and) or | (or), each in its own brackets: df[(df['Computer'] >= 80) & (df['Gender'] == 'M')].
Here are six students’ Computer marks. Change the condition and see which rows pass it, and what print() shows.
Writing a CSV file
A DataFrame’s to_csv() method writes it to a CSV file.
Step 1: Import Pandas: import pandas as pd.
Step 2: Make a DataFrame with pd.DataFrame(data, columns=…). The data are the records, here a list with one list for each row, and columns gives the column names:
header = ['Name', 'M1 Score', 'M2 Score']data = [['Sanskar', 62, 80], ['Sambriddhi', 45, 56], ['Aurora', 85, 98]]data = pd.DataFrame(data, columns=header)Step 3: Write it with to_csv(). Its form is DataFrame.to_csv(filename, sep=",", index=False): the separator is a comma unless you give another, and index=False leaves out the row numbers.
data.to_csv("Stu_data.csv", index=False)Stu_data.csv
Name,M1 Score,M2 ScoreSanskar,62,80Sambriddhi,45,56Aurora,85,98Without index=False, the file would get an extra first column holding 0, 1, 2, with no name: ,Name,M1 Score,M2 Score, then 0,Sanskar,62,80.
A DataFrame can also be made from a dictionary of columns, each column’s name with its list of values:
import pandas as pddata = { 'Product': ['Laptop', 'Smartphone', 'Tablet'], 'Price': [75000, 15000, 20000], 'Quantity': [3, 10, 5]}df = pd.DataFrame(data) # make a DataFramedf.to_csv('products.csv', index=False) # write it to a CSV fileprint("Data written to products.csv successfully.")Output
Data written to products.csv successfully.products.csv
Product,Price,QuantityLaptop,75000,3Smartphone,15000,10Tablet,20000,5Exercise: files and Pandas
1. Choose the correct answer
i. Which Python library is particularly useful for simplifying the handling of structured data, like CSV files?
Pick an answer to see why.
ii. What is the main function used in Pandas to read data from a CSV file?
Pick an answer to see why.
iii. When reading a CSV file with Pandas, which parameter of read_csv() is used to give the separator between values?
Pick an answer to see why.
iv. Which attribute of a Pandas DataFrame gives the header (field) names after reading a CSV file?
Pick an answer to see why.
v. Which Pandas method is used to write a DataFrame to a CSV file?
Pick an answer to see why.
vi. When writing a DataFrame to a CSV file with to_csv(), what does index=False do?
Pick an answer to see why.
vii. What separator does Pandas use by default when reading or writing CSV files?
Pick an answer to see why.
viii. Which mode should be used with the built-in open() function to read a file?
Pick an answer to see why.
ix. Which mode of open() overwrites the file if it exists, or creates a new file if it doesn’t?
Pick an answer to see why.
x. Which Pandas function is used to create a DataFrame from a dictionary or a list of lists?
Pick an answer to see why.
2. Write short answers to these questions
What are the main advantages of using the Pandas library for file handling in Python?
Answer
Explain what a CSV file is and why it is a common format for exchanging data.
Answer
What is the first step you need to take to use the Pandas library in your Python program for file handling?
Answer
Describe the basic syntax for reading a CSV file into a Pandas DataFrame.
Answer
How can you access one column of data after reading a CSV file into a Pandas DataFrame? Give an example.
Answer
Explain the basic syntax for writing a Pandas DataFrame to a CSV file.
Answer
What happens if you try to open a file that doesn’t exist in read ("r") mode with the built-in open() function?
Answer
Explain the difference between write ("w") mode and append ("a") mode when opening a file.
Answer
Why is it important to close a file after reading or writing (even when using Pandas)?
Answer
3. Write long answers to these questions
Write the steps to read data from a CSV file using Pandas in Python, with a simple program that imports the Pandas library and reads the CSV file.
Answer
You have a CSV file named student_data.csv with the columns Name, Age and Grade. Write a Python program using Pandas to (a) read the data from the file into a DataFrame, (b) print the first 5 rows of the DataFrame, (c) calculate the average age of the students, and (d) create a new DataFrame containing only the students with a Grade of “A”.
Answer
4.7 Data visualization
A table of a thousand numbers hides what it means; a single chart can show it at a glance. Data visualization means showing data as charts and graphs, so that patterns, trends and connections in it can be seen and understood easily.
Today businesses, hospitals, governments and scientists all make decisions from data, and an enormous amount of new data is made every day. Visualization is how people make sense of it and share what they find: a shop sees which month it sells most, a doctor sees a fever rising, a school sees which subjects need more help.
Python has several libraries for visualization, each with its own strengths:
- Matplotlib: the most used, for ordinary charts such as line graphs, bar charts and pie charts.
- Seaborn: built on Matplotlib, makes attractive, colorful charts of statistics with less code.
- Plotly: makes interactive charts that you can zoom, hover over and click.
The examples below use a small file of marks, Stu_data.csv (not the file of the same name written in 4.6: this one has a Gender and a Marks column):
Stu_data.csv
Name,Gender,MarksSanskar,M,62Sambriddhi,F,45Aurora,F,85Bishal,M,74Kiran,M,90Matplotlib
Matplotlib is Python’s most popular plotting library. It is a low-level library: you control every detail of a chart, but you often have to write more code to do it. Install it from the command prompt with pip install matplotlib (or conda install matplotlib, for the Anaconda version of Python), and import its pyplot module:
import matplotlib.pyplot as pltScatter plot
A scatter plot puts a dot for each pair of values, to show whether two quantities are related, such as hours of study and marks. Matplotlib draws one with scatter():
import pandas as pdimport matplotlib.pyplot as pltdataset = pd.read_csv("Stu_data.csv") # read the dataplt.scatter(dataset['Name'], dataset['Marks'])plt.title("Scatter Plot")plt.xlabel('Name')plt.ylabel('Marks')plt.show()plt.title() gives the chart a heading; plt.xlabel() and plt.ylabel() label the horizontal and vertical axes; plt.show() opens the window with the chart. (A scatter plot is clearest when both axes are numbers; with names along the x-axis, it shows each student’s marks as a dot.)
Bar chart
A bar chart shows categories as rectangular bars whose lengths are their values, so they are easy to compare. plt.bar(x, y) takes the categories first, then the values:
import pandas as pdimport matplotlib.pyplot as pltdata = pd.read_csv("Stu_data.csv")plt.bar(data['Name'], data['Marks'])plt.title("Bar Chart")plt.xlabel('Name')plt.ylabel('Marks')plt.show()The categories go on the x-axis and the values give the bars their heights. Swap them, as in plt.bar(data['Marks'], data['Name']), and the chart no longer matches its axis labels.
Pie chart
A pie chart shows how a whole is divided into parts: each slice’s share of the circle is its share of the total. autopct writes each slice’s percentage on it; '%1.1f%%' means one decimal place followed by a % sign.
import matplotlib.pyplot as pltlabels = ['A', 'B', 'C', 'D']sizes = [20, 30, 25, 25]plt.pie(sizes, labels=labels, autopct='%1.1f%%')plt.title("Pie Chart Example")plt.show()Seaborn
Seaborn is a library for attractive, informative charts of statistics. It is built on top of Matplotlib and works well with Pandas DataFrames, and it makes complicated charts with fewer lines of code: line plots, bar plots, heatmaps (a grid of colors showing values) and more. Install it with pip install seaborn. It is often used in Jupyter Notebook, which shows each chart right under the code that made it.
Seaborn’s lineplot() draws a line plot; give it the DataFrame as data, and the columns for the axes by name:
import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltdataset = pd.read_csv("Stu_data.csv")sns.lineplot(x='Name', y='Marks', data=dataset)plt.show()Seaborn draws the chart with Matplotlib, so plt.show() still opens the window.
Plotly
Plotly is a free, open-source library for interactive charts: you can hover over a point to see its value, zoom in, move about and save the picture. It makes 3-D charts, scientific and statistical charts and financial charts. Plotly charts open in a web browser or in Jupyter Notebook, and can be saved as web pages (HTML files). Install it with pip install plotly. Its simplest part is plotly.express, imported as px, which makes a whole chart from a DataFrame in one line; each function takes the DataFrame and the names of its columns.
Scatter plot, with px.scatter(). The color argument colors each dot by the values of another column, and adds a legend:
import pandas as pdimport plotly.express as pxdata = pd.read_csv("Stu_data.csv")fig = px.scatter(data, x='Name', y='Marks', color='Gender')fig.show()Plotly opens its charts in a web browser, so run this program in Thonny or Jupyter.
Line chart, with px.line():
import pandas as pdimport plotly.express as pxdata = pd.read_csv("Stu_data.csv")fig = px.line(data, x='Name', y='Marks')fig.show()Plotly opens its charts in a web browser, so run this program in Thonny or Jupyter.
Bar chart, with px.bar():
import pandas as pdimport plotly.express as pxdata = pd.read_csv("Stu_data.csv")fig = px.bar(data, x='Name', y='Marks', color='Gender')fig.show()Plotly opens its charts in a web browser, so run this program in Thonny or Jupyter.
| Matplotlib | Plotly | |
|---|---|---|
| Charts | still pictures | interactive: hover, zoom, click |
| Where they show | a window, or saved as a picture (PNG) | a web browser or notebook; saved as HTML |
| Code | more lines; every detail can be controlled | one line with plotly.express for a complete chart |
| Best for | printed reports, simple charts | exploring data, charts on websites |
Which chart answers “Which day sold most?”, and which answers “How did sales change through the week?” Try each kind in the chart maker.
Which chart is best to show what share of a family’s monthly spending goes on food, rent, school fees and transport?
Pick an answer to see why.
Solved examples
Code practice
Write each program yourself first; then open the model program. Where a question asks for a subprogram, write a function that does the job itself, such as printing the answer, and returns nothing (a void function); a function works out the answer and returns it.
The variables’ values, line by line, make a trace table: drawing one on paper is the surest way to work out a program’s output in an exam. Watch a and b move along the series.
On paper, the trace table for 123 has a row for each round of the loop:
num |
digit (num % 10) |
total |
num // 10 |
|---|---|---|---|
| 123 | 3 | 0 + 3 = 3 | 12 |
| 12 | 2 | 3 + 2 = 5 | 1 |
| 1 | 1 | 5 + 1 = 6 | 0 |
Now num is 0, so num > 0 is false and the loop stops: the function returns 6.
Exercise
1. Choose the correct answer
i. What is the main goal of data visualization?
Pick an answer to see why.
ii. Which Python library is popular for creating basic graphs like line charts and bar charts?
Pick an answer to see why.
iii. Which type of plot uses dots to show the relation between variables?
Pick an answer to see why.
iv. What type of chart uses rectangular bars to represent categories of data?
Pick an answer to see why.
v. Which data visualization library is built on Matplotlib and gives more advanced statistical charts?
Pick an answer to see why.
vi. Which Plotly method is used to create a scatter plot?
Pick an answer to see why.
vii. Which Plotly Express function is used to create a line chart?
Pick an answer to see why.
viii. Which Matplotlib function is used to create a pie chart?
Pick an answer to see why.
ix. Which Plotly Express function is used to create a bar chart?
Pick an answer to see why.
2. Write short answers to these questions
Define data visualization in your own words.
Answer
Why is data visualization important for businesses and analysts?
Answer
Name three popular Python libraries for data visualization.
Answer
What feature of Matplotlib gives both freedom and the need for more code?
Answer
What type of data is usually shown with a bar chart?
Answer
What is Seaborn built on, and what kind of charts does it mainly make?
Answer
What key feature of Plotly sets it apart from Matplotlib?
Answer
In Matplotlib, what do plt.xlabel() and plt.ylabel() do?
Answer
What type of data is best shown with a pie chart?
Answer
What is the purpose of the color argument in Plotly Express functions?
Answer
3. Write long answers to these questions
Explain the importance of data visualization in data analysis.
Answer
Compare Matplotlib and Plotly for data visualization in Python: their key features, strengths and weaknesses, especially their ease of use, interactivity and the control they give over line charts, pie charts and bar charts.
Answer
Explain how to create a basic line chart, bar graph and pie chart using Matplotlib. Include the import statement, example data, and the key functions used to create and show each chart.
Answer
A Pandas DataFrame holds a year’s sales data for different product categories, with the columns Month, Category and Sales. Outline the steps and write Python code (with Matplotlib or Plotly) to make: (a) a line chart of the total sales trend over the months, for all categories together; (b) a bar graph comparing the total sales of each category for the whole year; (c) a pie chart of each category’s percentage of the year’s total sales.
Hint
Answer
4. Practical questions
Write a Python program to take two numbers as input and print their sum, difference, product and quotient.
Answer
Write a program that takes a user’s name as input and prints a greeting message using the print() function.
Answer
Create a Python program that takes an integer from the user and checks whether it is positive, negative or zero, using an if-elif-else statement.
Answer
Write a program that accepts two numbers from the user and swaps their values without using a third variable.
Answer
Create a program that takes a sentence as input and counts the number of vowels in it.
Answer
Write a Python program to create a new file called data.txt and write the sentence “Hello, this is a test file.” into it.
Answer
Change the program above to append the sentence “This is an appended line.” to the same file.
Answer
Write a program that reads a file and prints its content on the screen.
Answer
Write a Python program using the csv module to create a CSV file students.csv with the columns Name and Marks, and add three student records.
Answer
Write a program that reads the data from students.csv and displays it.
Answer
Using Pandas, read a CSV file and print its first five rows.
Answer
Write a Pandas program to create a DataFrame from a dictionary and save it as a CSV file.
Answer
Using Pandas and Matplotlib, read data from a CSV file and draw a pie chart of product sales.
Answer
Write a Python function that takes two numbers as input and returns their sum.
Answer
Create a function that calculates the area of a circle, given the radius as a parameter.
Answer
Write a function that checks whether a number is prime.
Hint
Answer
Write a function that takes a list of numbers and returns the largest number in the list.
Answer
Write a program that reads a file and handles the exception if the file does not exist.
Answer
Practice every question in the book, and keep track of the ones you miss →
A companion to your textbook, not a replacement for it: study from the book your school uses, and where the two differ, follow your teacher. Found a mistake? Please tell us.
