Unit 4 Programming in Python | Class 10 Guide

Unit 4 Programming in Python | Class 10 Guide
Class 10 · Unit 4

Programming in
& Python

A friendly Python guide for class 10 students, with simple explanations of functions, libraries, files, and charts.

๐Ÿ Python Basics ๐Ÿงฉ Functions ๐Ÿ“š Libraries ๐Ÿ“ CSV Files ๐Ÿ“Š Charts ๐Ÿ› ️ Practice Tasks

Programming gets easier the moment you stop trying to remember every rule and start practising small programs. In this unit, short exercises and tiny projects build confidence quickly.

We focus on clear, friendly explanations for functions, libraries, and file handling. Try the code examples, change them, and see what happens — that experimentation is how you learn.

When you prepare your project, keep it simple and explain each step. Writing a short note about what you did helps the ideas stick.

4.1
Python Basics RefresherBring back the old ideas first

Before learning the new parts of Python, it helps to remember the basics: variables, data types, if statements, loops, and input/output. These are the building blocks of every program.

๐Ÿ’ก Easy analogy Python is like a language, and the basic rules are the alphabet and grammar. Once you know them, you can write bigger programs without getting lost.
Variable
A named place to store data.
Condition
A decision based on yes/no or true/false.
Loop
A way to repeat work without writing the same code again and again.
Input/Output
Input means taking data from the user. Output means showing results.
Basics — try these
num = 5 name = "Asha" print("Hello", name) if num > 3: print("Greater than three") for i in range(3): print(i) age = int(input("Enter your age: ")) print("In five years you'll be", age + 5)
4.2
User-defined FunctionsMake your code reusable

A function is a block of code that does one job. A user-defined function is a function you write yourself. It helps you avoid repetition and keeps code neat.

๐Ÿง 
Why Functions Matter
ReuseWrite once, use many times.
Easy readingBig programs become easier to understand.
Less errorLess repeated code means fewer mistakes.
๐Ÿงพ
Important Ideas
ScopeWhere a variable can be used.
ParameterA value a function accepts.
ReturnThe value a function gives back.
Functions — examples to try
def greet(name): """Return a hello message for name.""" return "Hello, " + name print(greet("Asha")) def add(a, b=0): """Return sum of a and b. b has a default value.""" return a + b print(add(4, 5)) print(add(3)) def factorial(n): result = 1 for i in range(2, n+1): result *= i return result print(factorial(5))
4.3
Libraries and PackagesUsing ready-made tools

A library is a collection of useful code that someone else already made. A package helps organize those tools so you can import them into your program.

math
Helps with square roots, powers, and other math work.
random
Gives random numbers or random choices.
pandas
Good for working with tables and CSV files.
turtle
Used for drawing shapes and patterns on the screen.
matplotlib
Used to make graphs and charts.
Remember You do not need to create everything from scratch. Python libraries are like ready-made tools in a toolbox.
4.4
Turtle GraphicsDraw with code

Turtle graphics lets you draw by giving commands to a small cursor called a turtle. It is a fun way to learn coding because you can see the result immediately.

forward()
Moves the turtle ahead.
left() / right()
Turns the turtle left or right.
color()
Changes the drawing color.
begin_fill() / end_fill()
Used to color the inside of a shape.
๐Ÿ’ก Easy analogy Turtle is like a small robot pen. You tell it where to move, and it draws the path for you.
Turtle — draw a square
import turtle screen = turtle.Screen() pen = turtle.Turtle() pen.color("blue") for _ in range(4): pen.forward(100) pen.left(90) screen.bye()
4.5
Error Handling with try-exceptFixing problems without crashing

Sometimes a program makes a mistake. Instead of stopping suddenly, we can use try-except to handle the error politely.

๐Ÿ›ก️
Why It Helps
Prevents crashThe program can keep running.
Better messageYou can show a friendly error message.
⚠️
Common Example
Division by zeroTrying to divide by 0 causes an error.
Wrong inputTyping letters when numbers are needed can also break a program.
Example — safe division
try: num = int(input("Enter a number: ")) print(10 / num) except ValueError: print("That was not a number. Please enter digits only.") except ZeroDivisionError: print("Cannot divide by zero — try a different number.") except Exception: print("Something went wrong.")
Example — file open error handling
try: with open('data.txt', 'r') as f: print(f.read()) except FileNotFoundError: print('data.txt not found — create the file and try again.')
4.6
CSV Files with PandasWorking with tabular data

Pandas is a Python library that makes it easy to read and write table-like data. A CSV file is a simple text file where data is stored in columns separated by commas.

Read CSV
Bring file data into Python.
Write CSV
Save Python data into a CSV file.
Append CSV
Add new rows to an existing file.
DataFrame
A table-like structure used by Pandas.
Pandas example
import pandas as pd df = pd.read_csv("students.csv") print(df)
Pandas — write & append
import pandas as pd # write a new CSV df = pd.DataFrame({ 'student_id': [1001, 1002], 'name': ['Asha', 'Ramesh'] }) df.to_csv('students_out.csv', index=False) # append a new row new = pd.DataFrame({'student_id': [1003], 'name': ['Sita']}) new.to_csv('students_out.csv', mode='a', header=False, index=False)
Memory tip CSV is a simple table file. Pandas helps Python read it like a real table.
4.7
Data VisualizationShowing data with charts

Data becomes easier to understand when we turn it into a chart. A chart can quickly show patterns, comparisons, and changes.

๐Ÿ“ˆ
Line Chart
Best for trendsShows how something changes over time.
๐Ÿ“Š
Bar Graph
Best for comparisonShows which item is bigger or smaller.
๐Ÿฅง
Pie Chart
Best for parts of a wholeShows how a total is divided into pieces.
Project idea Make a small program that reads CSV data and shows it using a bar, line, or pie chart.
Matplotlib — quick charts
import matplotlib.pyplot as plt # line chart x = [1, 2, 3, 4] y = [10, 20, 15, 30] plt.plot(x, y) plt.title('Line Chart') plt.show() # bar chart names = ['Asha', 'Ramesh', 'Sita'] scores = [80, 75, 92] plt.bar(names, scores) plt.title('Scores') plt.show() # pie chart parts = [40, 30, 30] labels = ['A', 'B', 'C'] plt.pie(parts, labels=labels, autopct='%1.1f%%') plt.title('Parts of a Whole') plt.show()
๐Ÿง  Quick Quiz
Question 1
Why do we use user-defined functions?
To reuse code, reduce repetition, and keep programs neat.
Question 2
What does Pandas help us do?
It helps us work with table-like data and CSV files.
Question 3
What is try-except used for?
It handles errors so the program does not crash suddenly.
Question 4
Which chart is useful for showing parts of a whole?
A pie chart is best for showing parts of a whole.
Netra Koirala

Netra Koirala

Computer Science Educator

Passionate computer science educator and author. Provides free study notes, practical guides, and tutorials for Class 9, 10, 11, 12, and B.Sc CSIT students in Nepal. Years of teaching experience in computer science fundamentals.

Computer Science notes, tutorials, MCQs, and educational resources for Nepal students. Covering Class 9, SEE preparation, Class 11, Class 12, SLC, programming, DBMS, networking, HTML, JavaScript, PHP, OOP and more.

Featured Post

Grade 10 Computer Science: Specification Grid & Model Questions

Specification Grid & Model Questions of Computer Science | Grade 10 ๐Ÿ“š Examination Resource Specification Grid & M...

Followers