Unit 4: Programming in Python – Class 10 SEE Computer Science Notes
Importantedunotes.com
Back to Computer Notes

Welcome to Chapter 3 As you write more Python code, you’ll quickly realize that you don’t always need to build everything from scratch. Just like a builder doesn’t forge their own hammer, programmers use pre-built tools.

Python provides us with amazing toolboxes called modules, packages, and libraries to make our lives vastly easier. Let’s explore how to use these tools to add powerful features to our code, and later, how to handle the inevitable errors that pop up when programming!

1. Concept of Library, Packages, and Error Handling

4.1 Modules, Packages, and Libraries

To keep code organized and maintainable, programmers break large programs into smaller, handleable units called Modules. Think of a module as a single file of Python code containing a few useful, related functions.

When you group several related modules together, you get a Package. A package is simply a container (like a digital folder) that holds various functions to perform specific tasks. For example, a math package might include a sqrt() function to calculate square roots. Packages are brilliant because they ensure the reusability of code—you write it once and use it anywhere.

When you gather many packages and modules together to serve a massive, overarching application, you create a Library. A library is a massive collection of code that caters to a specific type of need.

Commonly Used Python Libraries:

NumPy: A massive library designed for science and mathematics. It supports huge data arrays and tons of complex mathematical functions.
Pandas: The ultimate tool for data manipulation. It helps you analyze, clean, and work with different kinds of large datasets (think of it as Excel on steroids).
Matplotlib: A library dedicated entirely to creating charts, static or interactive plots, and visualizations. It is very frequently used alongside Pandas.

4.2 Importing and Using Standard Libraries

Python comes with a set of standard libraries that provide built-in modules to perform common tasks such as file handling, complex mathematics, and system operations. To use the tools hidden inside these packages, we have to bring them into our Python source file using the import statement. We can access specific parts of a package using the dot operator (.).

Python gives us four primary ways to import and use libraries:

1. Import the entire module:

This brings in the whole toolbox. You must type the module name followed by a dot to use its tools.

import math
print(math.sqrt(25))  # Output: 5.0

2. Import a specific function:

If you only need one specific tool, you can import just that function. You no longer need to use the prefix dot operator.

from math import sqrt
print(sqrt(25))       # Output: 5.0

3. Import a module with an Alias (Shortcut):

If a library has a long name, you can give it a nickname using the as keyword to save time typing.

import datetime as dt
print(dt.datetime.now()) # 'dt' acts as a handy shorthand for 'datetime'

4. Import all functions from a module:

You can use the asterisk (*) to import absolutely every tool from the module directly into your workspace.

from math import *
print(sin(90))  # Output depends on radians

4.3 Deep Dive into Popular Python Libraries

Libraries are planned and built by engineers to allow you to rapidly get to common functionalities, perform complex operations, and effortlessly reuse code. Let’s look at a few essential ones.

1. Math Library

The math library is built directly into Python. It provides access to mathematical operations that are not covered by default. It includes functions for mathematical constants (math.pi), trigonometry (sin(), cos(), tan()), logarithms (log()), and power functions (pow()).

import math
x = math.sqrt(256)
print("Square root is", x)

2. Random Library

The random library is used to generate random numbers and provide random selections. It is generally used for games, simulations, or security purposes.
Key functions include randrange() (returns a random number in a range), randint() (returns a random integer), and choice() (returns a random item from a list or string).

import random
print(random.randint(1, 10)) 
print(random.choice(['Apple', 'Banana', 'Orange']))

3. Pandas Library

Pandas offers necessary features for effortlessly manipulating, analyzing, and managing large datasets. It uses powerful data structures (like DataFrames) for manipulating numerical tables and time series. To use Pandas, you must first install it using your terminal command: $ pip install pandas.

import pandas as pd
data = {'Name': ['Shyam', 'Sanskar'], 'Age': [25, 30]}
df = pd.DataFrame(data)
print(df)

4. Matplotlib Library

Matplotlib is a low-level graph plotting library created by John D. Hunter that serves as a utility for high-quality visualizations. You must install it using pip install matplotlib. It can create line plots (relationships between x and y-axis), bar plots (numeric vs categoric values), and pie charts (percentages of a whole).

4.4 Graphics Using Turtle

The turtle module is a fun, pre-built library in Python used to create graphical representations on your screen using a digital cursor known as the “turtle”. It provides a simple interface for drawing shapes, lines, and animations, making it an excellent tool for teaching programming through interactive graphics.

Why Use the Turtle Module?

Easy Visualization: It gives a basic and fun approach to learning abstract programming concepts like loops and functions.
Interactive Learning: Users can command the turtle with Python to set directions and draw shapes.
Enhances Creativity: Absolute novices can make compelling geometric patterns and designs with very simple code.
Simplified Debugging: Because the output is visual, it is very easy to see exactly where your code went wrong.

Turtle Motion & Drawing Commands

You can control exactly how the turtle moves and draws on the digital canvas:

Moving: forward(distance) or fd(): Moves the turtle forward. backward(distance) or bk(): Moves the turtle backward without changing its heading.
Turning: right(angle) or rt(): Turns the turtle clockwise. left(angle) or lt(): Turns the turtle counterclockwise.
Drawing Controls: penup(): Lifts the turtle off the canvas (stops drawing). pendown(): Puts the turtle’s tail back down (starts drawing).
Colors and Filling: color(): Changes ink color. fillcolor(): Chooses color for filling a shape. begin_fill() & end_fill(): Tells the turtle when to start and stop filling a closed shape.
Changing the Cursor Shape: shape(): Changes the icon (e.g., “arrow”, “turtle”, “circle”, “square”).

Example: Drawing a Filled Circle

import turtle
t = turtle.Turtle()
r = int(input("Enter the radius of the circle: "))
col = input("Enter the color name (e.g., blue): ")

t.fillcolor(col)
t.begin_fill()
t.circle(r)
t.end_fill()
turtle.done()

4.5 Error Handling: Errors and Exceptions

As a programmer, you know that errors are an inevitable part of the coding process. No matter how well you plan, things can (and often do) go wrong. Error handling is a critical aspect of programming that empowers you to identify, manage, and resolve errors, ensuring your code remains robust and maintainable.

Types of Errors

An error is an issue that prevents the program from completing its task.

1. Syntax Errors: These occur when your code violates the grammatical rules of Python. If you miss a colon or spell a keyword wrong, Python refuses to run the code.
2. Runtime Errors: These occur after the program has successfully compiled and is actively running. A classic example is attempting to divide a number by zero.
# This will cause a runtime error
divide_by_zero = 7 / 0
3. Logical Errors: These occur when the program runs perfectly without any crashes, but the final output is incorrect. These are bugs where the algorithm or math was implemented wrongly by the programmer.
4. Exceptions: Even if a statement is syntactically correct, it may cause an anomaly when executed (like a runtime error). Errors detected during execution are called exceptions. If an exception is not handled by your program, Python generates a fatal error message and halts execution entirely.

Exception Handling: Try-Except Blocks

To create stable systems, we must anticipate these errors and come up with alternative solutions using try, except, else, and finally blocks.

The try Block: Lets us test a block of code for errors. Python will “try” to execute it.
The except Block: If the try block throws an exception, Python immediately jumps here. This enables us to handle the error gracefully without crashing the program.
The else Block: Optional. This block runs only if no exceptions were raised in the try block.
The finally Block: This block always runs at the very end, regardless of whether an exception occurred or not. It is typically used for cleanup operations (like closing files).

Example:

try:
    print(10 / 0)
except ZeroDivisionError:
    print("You cannot divide by zero!")
finally:
    print("Execution completed.")

2. Python Sample Programs Reference

Here are standard, well-commented sample programs demonstrating the logic and syntax learned throughout this unit.

1. Take two numbers as input and print their sum:
x = int(input("Enter first number: "))
y = int(input("Enter second number: "))
print("Sum of", x, "and", y, "is", x + y)

2. Check if a number is positive, negative, or zero:
num = int(input("Enter a number: "))
if num > 0:
    print("The number is positive.")
elif num == 0:
    print("The number is zero.")
else:
    print("The number is negative.")

3. Ask for user age and determine if they are an adult or not:
age = int(input("How old are you? "))
if age >= 18:
    print("You are an adult!")
else:
    print("You are a teenager or a kid.")

4. Create a new file and write a message into it:
file = open("message.txt", "w")
file.write("Hello, welcome to file handling in Python!")
file.close()
print("File created and message written successfully.")

5. Function to calculate the area of a rectangle:
def area(length, width):
    return length * width

length = int(input("Enter length: "))
width = int(input("Enter width: "))
print("Area of the rectangle:", area(length, width))

6. Function to check if a number is even or odd:
def check_even_odd(num):
    if num % 2 == 0:
        return "Even"
    else:
        return "Odd"

num = int(input("Enter a number: "))
print("The number is:", check_even_odd(num))

7. Function to return the square and cube of a number:
def square_and_cube(n):
    return n ** 2, n ** 3

num = int(input("Enter a number: "))
sq, cb = square_and_cube(num)
print("Square:", sq, "Cube:", cb)

8. Using a for loop to print numbers from 1 to 10:
for i in range(1, 11):
    print(i)

9. Using a while loop to find the sum of the first 10 natural numbers:
sum_val = 0
i = 1
while i <= 10:
    sum_val += i
    i += 1
print("Sum of first 10 natural numbers:", sum_val)

10. Print all even numbers from 1 to 20 using a for loop:
for i in range(2, 21, 2):
    print(i)

11. Function to calculate simple interest:
def simple_interest(principal, time, rate=10):
    return (principal * time * rate) / 100

p = float(input("Enter Principal Amount: "))
t = float(input("Enter Time in Years: "))
print("Simple Interest:", simple_interest(p, t))

Exercise 1: Choose the correct answer.

Select an option to view the correct answer and justification.

a) A collection of modules that together supply to specific needs or applications is called a:
1. Module
2. Package
3. Library
4. Function
Correct Answer: 3. Library
Justification: A library is defined as an overarching collection of modules and packages designed to fulfill a specific type of application or need (like NumPy for science).
b) Which of the following is a popular Python library used for data manipulation and analysis?
1. Math
2. Random
3. Pandas
4. Turtle
Correct Answer: 3. Pandas
Justification: Pandas is a library specifically designed to offer powerful tools for effortlessly manipulating, analyzing, and managing large datasets.
c) What is a container that contains various functions to perform specific tasks in Python?
1. Module
2. Library
3. Package
4. Function
Correct Answer: 3. Package
Justification: A package is a container (like a folder) that houses various modules and functions to perform specific tasks and ensure code reusability.
d) Which statement is used to access modules or files from a Python package?
1. include
2. use
3. import
4. access
Correct Answer: 3. import
Justification: The import keyword is the standard Python command used to load external packages and modules into your current script.
e) Which of the following is NOT a standard way to import a module in Python?
1. import module_name
2. from module_name get function_name
3. import module_name as alias
4. get function_name from module_name
Correct Answer: 4. get function_name from module_name
Justification: Python uses the from and import keywords. It never uses the get keyword in standard module importing logic.
f) Which Python library provides functions for generating random numbers?
1. Math
2. Random
3. Pandas
4. Matplotlib
Correct Answer: 2. Random
Justification: The random library is exclusively used to generate random numbers and perform random selections (like randint() or choice()).
g) What type of error occurs when the code violates the rules of the programming language’s syntax?
1. Runtime Error
2. Logical Error
3. Syntax Error
4. Exception
Correct Answer: 3. Syntax Error
Justification: Syntax errors occur when you make a grammatical mistake that breaks the rules of Python (like missing a colon), preventing the code from compiling.
h) Errors detected during program execution are called:
1. Syntax Errors
2. Logical Errors
3. Exceptions
4. Warnings
Correct Answer: 3. Exceptions
Justification: The text specifies that errors detected actively during execution (which are a type of runtime error) are formally referred to as exceptions, which can be handled using try-except blocks.
i) Which block is used to test a block of code for potential errors in Python?
1. catch
2. handle
3. try
4. error
Correct Answer: 3. try
Justification: The try block allows you to execute a risky block of code. Python will “try” to run it and monitor it for any exceptions.
j) Which block in error handling always executes, regardless of whether an exception occurred or not?
1. else
2. finally
3. except
4. try
Correct Answer: 2. finally
Justification: The finally block is guaranteed to run at the absolute end of the error-handling sequence, making it perfect for releasing resources or closing files.

Exercise 2: Write short answers to these questions.

a) Define the term “module” in the context of Python programming. 2 Marks
A module is a smaller, handleable unit of code. It is essentially a single Python file containing related functions and variables that can be imported and reused in other programs.

b) What is the relationship between modules and libraries in Python? 2 Marks
A module is a single file of code. A library is a massive collection of these modules (along with packages) grouped together to supply solutions for a specific application or need, like data science or visualization.

c) Give an example of a built-in Python library and its purpose. 2 Marks
The math library is a built-in Python library. Its purpose is to provide access to complex mathematical operations, such as trigonometry (math.sin()), logarithms, and square roots (math.sqrt()).

d) Explain why packages are useful for code organization and reusability. 2 Marks
Packages act as containers that organize related modules together. They are useful because they allow programmers to write a function once, store it in a package, and seamlessly reuse that identical code in hundreds of different projects without having to rewrite it.

e) What is the purpose of using an alias when importing a module in Python? Provide an example. 2 Marks
An alias is used to give a library a shorter “nickname” to save time when typing out its functions in your code.
Example: import pandas as pd. Now, instead of typing pandas.DataFrame(), you only have to type pd.DataFrame().

f) Name two functions provided by the Python math library. 2 Marks
Two functions provided by the math library are math.sqrt() (calculates the square root of a number) and math.pow() (calculates the power of a number).

g) What is a runtime error? Give an example of a situation that might cause one. 2 Marks
A runtime error occurs after a program has compiled successfully and is actively executing. It happens when the program attempts an impossible or illegal operation.
Example: Asking the computer to divide a number by zero (7 / 0) will cause a runtime error.

h) Explain the difference between an error and an exception in Python. 2 Marks
An “Error” (like a Syntax error) usually indicates a fundamental problem with the code’s grammar that prevents it from running at all. An “Exception” is a specific type of runtime anomaly that happens during active execution; exceptions are not unconditionally fatal because programmers can write try-except blocks to catch and handle them safely.

i) What is the role of the except block in a try-except statement? 2 Marks
The except block acts as the safety net. If the code inside the try block fails and throws an exception, Python instantly jumps to the except block to execute alternative code, preventing the entire program from crashing.

j) When is the else block in a try-except-else statement executed? 2 Marks
The else block is executed only if the code inside the try block succeeds completely without raising any exceptions.

Exercise 3: Write long answers to these questions.

a) Explain the concepts of Python libraries and packages, highlighting their importance in software development. 4 Marks

In software development, writing every single line of code from scratch is highly inefficient. To solve this, Python utilizes packages and libraries. A package is a container (or directory) that holds various related Python files (called modules). It ensures code is organized logically. A library takes this a step further; it is a massive collection of packages and modules geared toward a specific application.

Their importance cannot be overstated: they guarantee code reusability. Because libraries exist, developers can instantly import thousands of lines of pre-tested, highly optimized code to perform complex tasks (like manipulating datasets or drawing graphics) rather than wasting months inventing the tools themselves.


b) Introduce three popular Python libraries mentioned in the text: Pandas, Turtle, and Matplotlib. For each library, briefly describe its primary purpose and provide a simple example of how it can be used in a Python program. 4 Marks
Pandas: Used for manipulating, analyzing, and managing large datasets. It allows users to organize data into powerful tables called DataFrames.
Example: import pandas as pd -> df = pd.DataFrame({'Name': ['Shyam']})
Turtle: A pre-built library that provides a digital canvas and cursor (the turtle) to draw interactive shapes and animations. It is great for teaching programming visually.
Example: import turtle -> t = turtle.Turtle(); t.forward(50)
Matplotlib: A high-quality graph plotting library used for data visualization. It transforms raw numbers into line plots, bar charts, and pie charts.
Example: import matplotlib.pyplot as plt -> plt.plot(x_values, y_values)

c) Discuss the different types of errors that can occur in Python programs: syntax errors, runtime errors, and logical errors. Provide an example of each type and explain how they can impact the execution and correctness of a program. 4 Marks
Syntax Errors: These are grammatical mistakes in your code. They impact the program by preventing it from starting entirely because Python cannot understand the instructions.
Example: Missing a closing parenthesis print("Hello".
Runtime Errors: The code is grammatically correct and begins running, but it hits a wall by attempting an illegal operation, causing a sudden crash during execution.
Example: Trying to divide by a variable that holds a zero result = 10 / 0.
Logical Errors: The most dangerous type. The program runs perfectly without crashing, but because the programmer’s underlying algorithm or math formula was flawed, it produces the incorrect output.
Example: Writing area = length + width instead of length * width. The program thinks it succeeded, but the data is entirely wrong.

d) Explain the importance of error handling in Python. 4 Marks

Error handling is a critical aspect of creating robust software. In the real world, programs interact with unpredictable factors: users type text when asked for numbers, network connections drop, and files go missing. If a program lacks error handling, encountering any of these issues will result in a fatal crash, destroying user trust and potentially losing unsaved data.

By utilizing Python’s try-except blocks, developers can anticipate these failures. Instead of the system shutting down, the error is safely “caught” by the except block, allowing the program to display a friendly warning message, execute a backup plan, and continue running smoothly. This greatly enhances the reliability, stability, and maintainability of the software.

📚 Also Read: Class 10 SEE Notes

Computer Science Units

Other Subjects

Scroll to Top