Unit: 4 Programming in Python
Complete Python programming notes covering functions, libraries, Turtle graphics, error handling, file handling, CSV with Pandas, and data visualization, based on the CDC syllabus.
4.1 Revision of the Basics of Python
Before moving into more advanced topics, it’s worth quickly revisiting the core Python concepts covered in Class 9, since everything in this unit builds directly on them.
- Variables and data types : storing values such as numbers (int, float), text (str), and True/False values (bool)
- Operators : arithmetic (+, -, *, /), relational (==, >, <), logical (and, or, not), and assignment (=, +=)
- Conditional statements : using if, elif, and else to make decisions
- Loops : using for and while to repeat actions
- Lists and dictionaries : storing collections of related data
Quick example combining several of these basics:
numbers = [4, 8, 15, 16, 23, 42]
total = 0
for num in numbers:
if num % 2 == 0:
total += num
print(f"Sum of even numbers: {total}")4.2 User Defined Functions: Scope, Parameter, Argument, Return Type, Passing
A function is a named, reusable block of code that performs a specific task. Instead of rewriting the same code every time you need it, you define it once and simply call it whenever needed. A user-defined function is one that a programmer creates themselves, as opposed to Python’s built-in functions like print() or len().
Defining and Calling a Function
def greet():
print("Hello, welcome to Python!")
greet() # calling the functionThe def keyword defines a function, followed by the function’s name and parentheses. The code inside runs only when the function is called.
Parameter and Argument
A parameter is a variable listed inside a function’s parentheses when it’s defined, acting as a placeholder for a value the function expects to receive. An argument is the actual value passed into the function when it’s called.
def greet(name): # name is the parameter
print(f"Hello, {name}!")
greet("Sita") # "Sita" is the argumentReturn Type
A function can send a value back to wherever it was called from, using the return keyword. This lets you use the result of a function elsewhere in your program, rather than just printing it directly.
def add(a, b):
return a + b
result = add(5, 3)
print(result) # 8Scope
Scope refers to where in a program a variable can be accessed. A variable created inside a function (called a local variable) can only be used inside that function, and disappears once the function finishes running. A variable created outside all functions (called a global variable) can be accessed from anywhere in the program.
def show_message():
message = "Hello" # local variable, only exists inside this function
print(message)
show_message()
print(message) # This causes an error, since message does not exist outside the functionPassing Arguments
Arguments can be passed to a function in different ways, most commonly by position (matched in the order given) or by keyword (explicitly naming which parameter each value belongs to).
def student_info(name, age):
print(f"{name} is {age} years old")
student_info("Ram", 15) # positional
student_info(age=15, name="Ram") # keyword, order doesn't matter hereDefault Parameter Values
A function can also be given a default value for a parameter, used automatically if no argument is provided for it when the function is called.
def greet(name="Student"):
print(f"Hello, {name}!")
greet() # Hello, Student!
greet("Hari") # Hello, Hari!4.3 Concept of Library and Packages in Python
A library (also called a module) is a collection of pre-written functions and code that you can use in your own program, instead of writing everything from scratch. A package is a collection of related libraries/modules bundled together.
Python has a huge ecosystem of libraries, which is one of the biggest reasons it’s so popular instead of building complex features yourself, you can simply import a library that already does the job.
4.3.1 Importing and Use of Standard Libraries
To use a library in Python, you first need to import it using the import keyword.
import math print(math.sqrt(25)) # 5.0 print(math.pi) # 3.141592653589793
You can also import just one specific function from a library, if you don’t need the whole thing:
from math import sqrt print(sqrt(36)) # 6.0
4.3.2 Introduction to Popular Libraries
math: provides mathematical functions and constants, such as square roots, trigonometry, and rounding operations.
import math print(math.factorial(5)) # 120 print(math.ceil(4.3)) # 5
random : used to generate random numbers or make random selections, useful in games, simulations, or quizzes.
import random print(random.randint(1, 10)) # random whole number between 1 and 10 print(random.choice(["red", "blue", "green"])) # randomly picks one item
Pandas : a powerful library for working with structured, table-like data (similar to a spreadsheet), widely used for reading, analyzing, and manipulating data, including CSV files.
Turtle : a beginner-friendly graphics library used to draw shapes and pictures on screen by controlling a small on-screen “turtle” cursor that moves and draws as it’s given instructions.
Matplotlib : a library used to create charts and graphs, such as line charts, bar graphs, and pie charts, to visually represent data.
4.4 Graphics Using Turtle
The Turtle library lets you create drawings by giving movement and drawing instructions to a virtual “turtle” that leaves a trail as it moves, similar to drawing with a pen.
Basic Turtle Setup
import turtle t = turtle.Turtle()
This imports the turtle library and creates a turtle object named t, which you then control using various functions.
Common Turtle Functions
| Function | Purpose |
|---|---|
| forward(distance) | Moves the turtle forward by the given distance |
| backward(distance) | Moves the turtle backward |
| left(angle) | Turns the turtle left by the given angle |
| right(angle) | Turns the turtle right by the given angle |
| penup() | Lifts the pen so moving the turtle doesn’t draw a line |
| pendown() | Lowers the pen so moving the turtle draws a line again |
| color(“colorname”) | Sets the drawing (outline) color |
| fillcolor(“colorname”) | Sets the color used to fill a shape |
| shape(“shapename”) | Changes the turtle cursor’s appearance (e.g. “turtle”, “arrow”) |
Example: Drawing a Square
import turtle
t = turtle.Turtle()
t.color("blue")
for i in range(4):
t.forward(100)
t.right(90)
turtle.done()This moves the turtle forward 100 units and turns right 90 degrees, four times in a row, which draws a complete square.
Example: Drawing and Filling a Shape
import turtle
t = turtle.Turtle()
t.color("black")
t.fillcolor("yellow")
t.begin_fill()
for i in range(3):
t.forward(100)
t.left(120)
t.end_fill()
turtle.done()The begin_fill() and end_fill() functions mark the start and end of a shape that should be filled with the chosen fill color here, a triangle filled with yellow.
4.5 Error Handling: Errors and Exceptions, Try-Except Blocks
Even correctly written programs can encounter unexpected problems while running, such as a user entering text instead of a number, or trying to open a file that doesn’t exist. These problems are called exceptions, and if not handled, they cause the program to crash.
Common Types of Exceptions
- ZeroDivisionError : occurs when dividing a number by zero
- ValueError : occurs when a function receives a value of the correct type but an invalid value, such as converting the text “abc” into a number
- FileNotFoundError: occurs when trying to open a file that doesn’t exist
- TypeError : occurs when an operation is used on an incompatible data type
Try-Except Block
Python lets you handle these errors gracefully using a try-except block, so the program can respond to an error instead of crashing completely.
try:
num = int(input("Enter a number: "))
result = 10 / num
print(f"Result: {result}")
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Please enter a valid number!")Python first tries to run the code inside the try block. If an error matching one of the except blocks occurs, that specific block runs instead of the program crashing. This lets you show the user a helpful message and even let the program continue running afterward.
4.6 File Handling Using Pandas Library
4.6.1 Concept of File Handling in Python
File handling refers to the process of creating, reading, writing, and updating files directly from a Python program, allowing data to be saved permanently (persisted) even after the program stops running, rather than being lost when the program ends.
4.6.2 Concept of Modes of File Handling
When opening a file in Python, you specify a mode describing what you intend to do with it:
- “r” (Read) : opens a file only for reading; the file must already exist
- “w” (Write) : opens a file for writing, creating it if it doesn’t exist, and completely erasing its existing content if it does
- “a” (Append) : opens a file for writing, but adds new content to the end of the existing file instead of erasing it
# Writing to a file
file = open("notes.txt", "w")
file.write("This is my first line.\n")
file.close()
# Appending to a file
file = open("notes.txt", "a")
file.write("This line was added later.\n")
file.close()
# Reading a file
file = open("notes.txt", "r")
print(file.read())
file.close()4.6.3 Read and Write CSV File Using Standard Library (Pandas)
A CSV (Comma-Separated Values) file stores tabular data as plain text, with each line representing a row and commas separating each column’s value. The Pandas library makes reading and writing CSV files very simple.
Reading a CSV file:
import pandas as pd
data = pd.read_csv("students.csv")
print(data)
print(data.head()) # shows just the first 5 rowsWriting a CSV file:
import pandas as pd
data = {
"Name": ["Ram", "Sita", "Hari"],
"Age": [15, 14, 16],
"Class": [10, 9, 10]
}
df = pd.DataFrame(data)
df.to_csv("students.csv", index=False)Here, a Python dictionary is converted into a Pandas DataFrame (a table-like structure) using pd.DataFrame(), then saved as a CSV file using .to_csv(). Setting index=False prevents Pandas from adding an extra numbered column when saving.
4.7 Introduction to Data Visualization
Data visualization means representing data graphically using charts, graphs, and diagrams to make patterns, trends, and comparisons easier to understand at a glance than raw numbers alone. The Matplotlib library is one of the most widely used tools in Python for creating these visualizations.
Line Chart
Used to show how a value changes over time or across a sequence, such as tracking temperature changes throughout a week.
import matplotlib.pyplot as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temperature = [22, 24, 23, 26, 25]
plt.plot(days, temperature)
plt.title("Weekly Temperature")
plt.xlabel("Day")
plt.ylabel("Temperature (\u00b0C)")
plt.show()Bar Graph
Used to compare values across different categories, such as comparing marks scored in different subjects.
import matplotlib.pyplot as plt
subjects = ["Math", "Science", "English"]
marks = [88, 92, 79]
plt.bar(subjects, marks, color="skyblue")
plt.title("Marks by Subject")
plt.xlabel("Subject")
plt.ylabel("Marks")
plt.show()Pie Chart
Used to show how a whole is divided into proportional parts, such as showing the percentage of time spent on different daily activities.
import matplotlib.pyplot as plt
activities = ["Study", "Sleep", "Play", "Other"]
hours = [6, 8, 4, 6]
plt.pie(hours, labels=activities, autopct="%1.1f%%")
plt.title("Daily Time Distribution")
plt.show()The autopct="%1.1f%%" argument automatically displays each slice’s percentage on the chart itself.
Practical Tasks
- Demonstrate the structure of user-defined functions:
def calculate_area(length, width): area = length * width return area print(calculate_area(5, 3)) - Install and use packages and libraries (e.g. Pandas, Turtle, matplotlib) install using pip, then import and use them:
pip install pandas matplotlib
- Draw various shapes (circle, rectangle, polygons, etc.) and fill the colors using Turtle:
import turtle t = turtle.Turtle() # Circle t.color("blue") t.circle(50) # Rectangle t.penup() t.goto(150, 0) t.pendown() t.fillcolor("green") t.begin_fill() for i in range(2): t.forward(80) t.right(90) t.forward(40) t.right(90) t.end_fill() turtle.done() - Demonstrate reading and writing a CSV file using file handling with Pandas:
import pandas as pd data = {"Name": ["Ram", "Sita"], "Marks": [85, 90]} df = pd.DataFrame(data) df.to_csv("results.csv", index=False) read_data = pd.read_csv("results.csv") print(read_data) - Draw and plot a bar, line, and pie chart using data visualization tools with the matplotlib package : see the three examples in section 4.7 above.
Project Work
Using any Python platform, such as PyCharm, Jupyter Notebook, or Google Colab:
- Develop a simple project of your own, using libraries, user-defined functions, and a visualization tool covered in this unit (for example, a small project that reads data from a CSV file, processes it using a function, and displays the result as a chart).
- Prepare a simple report outlining the process you followed during development, including what libraries you used, what functions you created, and any challenges you faced.
Important Questions
- What is a function? Why are user-defined functions useful in programming?
- Differentiate between a parameter and an argument.
- What is the purpose of the return statement in a function?
- Differentiate between local and global scope with an example.
- What is the difference between passing arguments positionally and using keyword arguments?
- What is a library in Python? How is it different from a package?
- Write the Python statement used to import the entire math library, and one to import only the sqrt function from it.
- Name any three popular Python libraries and briefly describe what each is used for.
- What is the Turtle library used for? Name any four common Turtle functions.
- Write a short Turtle program to draw a square.
- What is the difference between penup() and pendown() in Turtle graphics?
- What is an exception in Python? Give two examples of common exceptions.
- What is the purpose of a try-except block? Explain with an example.
- What happens to a program if an error occurs and there is no exception handling in place?
- What is file handling? Why is it useful in programming?
- Differentiate between the “w” and “a” file handling modes.
- What happens to a file’s existing content if it is opened in “w” mode?
- What is a CSV file? Why is it commonly used for storing data?
- Write a short Pandas code snippet to read data from a CSV file named “data.csv”.
- What is data visualization, and why is it useful?
- Differentiate between a line chart, bar graph, and pie chart, and describe when each is best used.
- Which Python library is commonly used to create charts and graphs?
- Write a short matplotlib code snippet to create a bar graph comparing marks in three subjects.
