Unit 4
– Programming in Python
4.1 Revision of
the Basics of Python
Definition of I/O Statements in
Python
I/O (Input/Output) statements in
Python are built-in functions used to interact with the user by taking input
data and displaying output results. The input() function is used for accepting
data from the user, while the print() function is used for displaying
information or results on the screen.
1. Input Statement
The input statement in
Python is used to accept data from the user during program execution. The
input() function reads the value entered by the user and stores it in a
variable.
Example:
number = input("Enter number:
")
2. Print Statement
The output statement in
Python is used to display information or results on the screen. The print()
function is used to show text, values, variables, or expressions as output.
Example:
print("Hello, Python!")
Data Types and Variables in Python
1. Data Types
A data type defines the type
of data that a variable can store. Python provides different built-in data
types to store different kinds of values.
i. Integer (int)
An integer data type
represents whole numbers without decimal points. It can contain positive
numbers, negative numbers, and zero.
Examples:
..., -3, -2, -1, 0, 1, 2, 3, ...
Example in Python:
age = 25
ii. Float (float)
A float data type represents
numbers that contain decimal values.
Examples:
3.14, -0.5, 1.567
Example in Python:
price = 99.99
iii. String (str)
A string is a sequence of
characters such as alphabets, numbers, and special symbols enclosed within
single or double quotation marks.
Examples:
"Hello"
"Python@"
"Bhaktapur1"
"@#@#Kathmandu"
Example in Python:
name = "Ram"
iv. Boolean (bool)
A Boolean data type
represents logical values. It contains only two possible values: True or
False.
Examples:
is_student = True
has_mobile = False
v. Identifier
An identifier is a name used
to identify program elements such as variables, functions, classes, or other
objects in a Python program.
Examples:
student_name = "Ram"
total_marks = 500
2. Variables
A variable is a named memory
location used to store data values. In Python, a variable is created
automatically when a value is assigned to it.
Syntax:
variable_name = value
Example:
a = 15
name = "Python"
Here, a stores the value 15,
and name stores the string "Python".
Key Point:
- Variables
can store different types of data.
- Python
does not require declaring the data type of a variable before using it.
Operators and Expressions in Python
Operators
Operators are special symbols or
keywords used to perform specific operations on values or variables. They allow
us to perform calculations, comparisons, and logical operations in a Python
program.
An expression is a
combination of values, variables, and operators that produces a result.
Example:
10 + 20
Here, + is an operator, and 10 + 20
is an expression.
1. Arithmetic Operators
Arithmetic operators are used to
perform mathematical calculations such as addition, subtraction,
multiplication, and division.
|
Operator |
Name |
Example |
Result |
|
+ |
Addition |
10 + 20 |
30 |
|
- |
Subtraction |
10 - 20 |
-10 |
|
* |
Multiplication |
10 * 20 |
200 |
|
/ |
Division |
20 / 10 |
2 |
|
% |
Modulus (remainder) |
20 % 10 |
0 |
|
** |
Exponent (power) |
10 ** 2 |
100 |
|
// |
Floor Division |
9 // 2 |
4 |
2. Relational Operators
Relational operators are used to
compare two values. They return a Boolean result: True or False.
|
Operator |
Name |
Description |
Example |
|
== |
Equal to |
Checks whether two values are
equal |
5 == 5 → True |
|
!= |
Not equal to |
Checks whether two values are
different |
3 != 5 → True |
|
> |
Greater than |
Checks if one value is greater
than another |
7 > 5 → True |
|
< |
Less than |
Checks if one value is smaller
than another |
3 < 9 → True |
|
>= |
Greater than or equal to |
Checks if a value is greater or
equal |
8 >= 8 → True |
|
<= |
Less than or equal to |
Checks if a value is smaller or
equal |
4 <= 6 → True |
3. Logical Operators
Logical operators are used to
combine multiple conditions and make decisions based on logical relationships.
They return True or False.
|
Operator |
Name |
Description |
Example |
|
and |
Logical AND |
Returns True if both conditions
are True |
a and b |
|
or |
Logical OR |
Returns True if at least one
condition is True |
a or b |
|
not |
Logical NOT |
Reverses the result of a
condition |
not(a) |
Example:
age = 20
print(age > 18 and age < 30)
Output:
True
4. Assignment Operators
Assignment operators are used to
assign values to variables.
|
Operator |
Example |
Meaning |
|
= |
x = 10 |
Assigns value 10 to x |
|
+= |
x += 5 |
Adds 5 and assigns the result |
|
-= |
x -= 5 |
Subtracts 5 and assigns the
result |
|
*= |
x *= 5 |
Multiplies and assigns the result |
|
/= |
x /= 5 |
Divides and assigns the result |
Example:
x = 10
x += 5
print(x)
Output:
15
Conditional Statements in Python
A conditional statement in
Python is used to make decisions in a program. It executes a specific block of
code depending on whether a given condition is True or False.
Python provides different types of
conditional statements:
- if
statement
- if-else
statement
- if-elif-else
statement
- Nested
if statement
1. if Statement
The if statement is the
simplest conditional statement. It executes a block of code only when the given
condition is True.
Syntax:
if condition:
# statement to be executed when condition is True
Example:
# Program to check whether a number
is positive
number = int(input("Enter a
number: "))
if number > 0:
print("The number is positive.")
Output:
Enter a number: 5
The number is positive.
2. if-else Statement
The if-else statement is
used when we want to execute one block of code if the condition is True and
another block of code if the condition is False.
Syntax:
if condition:
# statement executed when condition is True
else:
# statement executed when condition is False
Example:
# Program to check age category
user_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? 20
You are an adult!
3. if-elif-else Statement
The if-elif-else statement
is used to check multiple conditions. The program executes the block of code
corresponding to the first True condition. If all conditions are False, the
else block is executed.
Syntax:
if condition1:
# code executed if condition1 is True
elif condition2:
# code executed if condition2 is True
else:
# code executed if all conditions are False
Example:
# Program to check whether a number
is 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: -5
The number is negative.
4. Nested if Statement
A nested if statement is an
if statement placed inside another if statement. It is used when a second
condition needs to be checked after the first condition becomes True.
Syntax:
if condition1:
# code executed if condition1 is True
if condition2:
# code executed if condition2 is True
else:
# code executed if condition2 is False
else:
# code executed if condition1 is False
Example:
age = int(input("Enter your
age: "))
if age >= 16:
print("You are eligible for citizenship.")
if age >= 18:
print("You are eligible to cast a
vote.")
else:
print("You are not eligible to
cast vote.")
else:
print("You are a minor.")
Output:
Enter your age: 20
You are eligible for citizenship.
You are eligible to cast a vote.
Summary Table
|
Conditional Statement |
Purpose |
|
if |
Executes code when a condition is
True |
|
if-else |
Chooses between two blocks of
code |
|
if-elif-else |
Checks multiple conditions |
|
Nested if |
Checks a condition inside another
condition |
✅ Conditional statements help
Python programs make decisions and control the flow of execution.
Iteration in Python
Iteration is the process of executing a
block of code repeatedly until a specified condition is satisfied. It helps to
perform repetitive tasks efficiently without writing the same code multiple
times.
Python mainly provides two types of
loops for iteration:
- for
loop
- while
loop
1. for Loop
A for loop is used to repeat
a block of code a specific number of times. It is generally used when the
number of iterations is already known.
Syntax:
for item in sequence:
# code to be executed for each item
Example:
# Program to print
"Programming" five times
for x in range(5):
print("Programming")
Output:
Programming
Programming
Programming
Programming
Programming
Explanation:
- range(5)
generates numbers from 0 to 4.
- The
loop executes 5 times and prints "Programming" each time.
2. while Loop
A while loop is used to
execute a block of code repeatedly as long as the given condition remains True.
It is used when the number of repetitions is not known in advance.
Syntax:
while condition:
# code to be executed
Example:
# Program to print numbers from 1
to 5
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Explanation:
- The
variable count starts from 1.
- The
loop continues until count becomes greater than 5.
- count
+= 1 increases the value of count after each iteration.
Difference Between for Loop and
while Loop
|
for Loop |
while Loop |
|
Used when the number of
repetitions is known |
Used when the number of
repetitions is unknown |
|
Works with sequences like list,
string, and range |
Works based on a condition |
|
Automatically controls iteration |
Requires manual updating of the
condition variable |
Summary
- Iteration → Repeating a task multiple
times.
- for
loop → Used
for fixed number of repetitions.
- while
loop → Used
for repeating until a condition becomes False. ✅
Python List
A Python list is a built-in
data type used to store multiple values or items in a single variable. A list
can store different types of data such as numbers, strings, and Boolean values.
Lists are ordered, changeable (mutable), and allow duplicate values.
Syntax:
list_name = [item1, item2, item3,
...]
Example:
thislist = ["Computer",
"Science", 20, True]
print(thislist)
Output:
['Computer', 'Science', 20, True]
Explanation:
- "Computer"
and "Science" are string values.
- 20
is an integer value.
- True
is a Boolean value.
- All
values are stored together in one list named thislist.
Python Dictionary
A Python dictionary is a
built-in data type used to store data in the form of key-value pairs.
Each key is unique and is used to access its corresponding value. Dictionaries
are ordered and changeable.
Syntax:
dictionary_name = {
key1: value1,
key2: value2
}
Example:
student = {
"name": "Ram",
"age": 15,
"grade": 10
}
print(student)
Output:
{'name': 'Ram', 'age': 15, 'grade':
10}
Accessing Dictionary Values:
print(student["name"])
Output:
Ram
Explanation:
- "name",
"age", and "grade" are keys.
- "Ram",
15, and 10 are their corresponding values.
- The
key is used to access the required value.
Difference Between List and
Dictionary
|
List |
Dictionary |
|
Stores multiple values in a
sequence |
Stores data as key-value pairs |
|
Values are accessed using index
numbers |
Values are accessed using keys |
|
Written using square brackets [] |
Written using curly brackets {} |
|
Example: ["Python", 10] |
Example:
{"subject":"Python"} |
✅ Lists are useful for storing
collections of items, while dictionaries are useful for storing related
information with labels (keys).
SECTION
1: MCQs
Questions
1.
Which statement is used to display output in Python?
a) input( ) b) print( ) c) display( ) d)
output( )
2.
Which of the following is NOT a valid Python data type mentioned in the text?
a) int b) float c)
character d)
bool
3.
What type of values does the Boolean data type hold?
a) Whole numbers b) Decimal numbers c) Text d)
True or False
4.
Which of the following is an example of a relational operator?
a) + b) * c)
= = d) and
5.
Which logical operator returns True if both conditions are true?
a) or b) not c)
and d) !=
6.
What is the purpose of the if statement in Python?
a) To
repeat a block of code
b) To define a function
c) To execute a block of code only if a condition is true
d) To store multiple items
7.
Which conditional statement allows you to check multiple conditions in
sequence?
a) if b) if-else c)
nested if d) if-elif-else
8.
What is the term for repeating a block of code multiple times?
a) Selection b) Iteration c) Condition d)
Assignment
9.
Which type of loop is used when you know the number of times you want to repeat
a block of code?
a) while loop b) for loop c) if loop d) nested loop
10.
Which data structure is used to store multiple items in a single variable as
shown:
["Computer",
"Science", 20, True]
a) String b) Tuple c)
List d)
Dictionary
SECTION
2: Short Answer Questions
1.
What is the primary function of the input() function in Python?
Ans: The input()
function is used to take input from the user.
2.
Provide an example of a string literal in Python.
Ans: A string
literal is just text written directly in the code, wrapped in quotes.
Example: "Hello"
3.
What is an identifier in Python programming?
Ans: An identifier
is the name given to variables, functions, or other objects.
Example: age = 16
4.
Explain the difference between the division operator (/) and floor division
operator (//).
Ans: / performs normal division and gives a decimal
result.
// performs floor division and
removes the decimal part.
Example:
print(10
/ 3) # 3.3333333333333335
print(10
// 3) # 3
5.
Define data types in Python.
Ans: Data types
specify the type of value a variable can store, such as int, float, string, and
boolean.
6.
What is the purpose of relational operators in Python?
Ans: Relational
operators are used to compare two values. They return either True or False
depending on the comparison.
7.
Describe the functionality of the else block in an if-else statement.
Ans: The else
block executes when the condition in the if statement is False.
8. What is a nested if statement?
Ans: A nested if
statement is an if statement inside another if statement, used to test multiple
conditions in sequence. It is used when a second condition needs to be checked
after the first condition is true.
9.
When would you use a for loop instead of a while loop?
Ans: A for loop is
used when the number of repetitions is known in advance.
10.
What is the role of the range( ) function?
Ans:
The range( ) function is used to generate a sequence of numbers, usually for
use in a for loop.
11.
Define a Python list and give one example.
Ans: A Python list
is a collection data type that stores multiple items in a single variable.
Lists are ordered, changeable (mutable), and allow duplicate
values.
Example:
marks = [85, 90, 78]
12.
What is iteration in programming?
Ans:
Iteration in programming is the process of repeating a block of code multiple
times.
It
is usually done using loops, such as for loops and while loops.
SECTION
3: Long Answer Questions
1.
Explain the different categories of operators in Python (arithmetic,
relational, logical) with examples.
Ans:
|
Category |
Purpose |
Operators |
Example |
Result |
|
Arithmetic Operators |
Perform mathematical calculations |
+, -, *, /, //, %, ** |
10 + 5 |
15 |
|
Relational Operators |
Compare two values |
==, !=, >, <, >=, <= |
10 > 5 |
True |
|
Logical Operators |
Combine or modify conditions |
and, or, not |
5 > 2 and 8 > 3 |
True |
2.
Describe the three main types of conditional statements in Python.
Ans: Here are the
three main types of conditional statements in Python:
if
Statement - The if
statement executes a block of code only if the condition is True.
Example:
age
= 18
if age >= 18:
print("Adult")
If
the condition is false, nothing happens.
if-else
Statement - The
if-else statement executes one block of code if the condition is True, and
another block if it is False.
Example:
age
= 16
if age >= 18:
print("Adult")
else:
print("Minor")
One
of the two blocks will always run.
if-elif-else
Statement - Used
when there are multiple conditions to check.
Example:
marks
= 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Python
checks conditions one by one. The first true condition runs, and the rest are
skipped.
3.
Explain the two types of loops in Python with examples.
Ans: Python has two
main types of loops:
for
Loop - A for loop
is used when you know how many times you want to repeat something or when you
are iterating over a sequence (like a list or range).
Example:
for
i in range(5):
print(i)
This
runs 5 times and prints numbers from 0 to 4.
Use
it when the number of iterations is known.
while
Loop - A while
loop runs as long as a given condition is True.
Example:
count
= 0
while count < 5:
print(count)
count += 1
This
continues until the condition becomes False.
Use
it when the number of iterations depends on a condition.
4.
Describe the four basic data types (int, float, string, boolean) with examples
and importance.
Ans: Here are the
four basic data types in Python:
Integer
(int) - An integer
is a whole number without a decimal point.
Example:
age
= 25
Importance:
Integers are used
for counting, indexing, and performing mathematical operations where whole
numbers are required.
Float
(float) - A float
is a number that contains a decimal point.
Example:
price
= 99.99
Importance:
Floats are
important when precision is needed in calculations involving fractions,
measurements, or financial data.
String
(str) - A string
is a sequence of characters enclosed in single or double quotes.
Example:
name
= "Deepak"
Importance:
Strings are used
to store and manipulate text such as names, messages, and user input.
Boolean
(bool) - A boolean
represents one of two values: True or False.
Example:
is_logged_in
= True
Importance:
Booleans are
essential for decision-making in programs, especially in conditional statements
and loops.
5.
Write a Python program that:
Prints
“Positive” if number > 0
Prints
“Negative” if number < 0
Prints
“Zero” if number = 0
If
positive, also checks if even or odd
number
= int(input("Enter a number: "))
if
number > 0:
print("Positive")
if number % 2 == 0:
print("Even")
else:
print("Odd")
elif
number < 0:
print("Negative")
else:
print("Zero")
4.2 User defined Functions: scope,
parameter, argument, return type, passing
Introduction to Functions
A function is
a block of organized and reusable code that performs a specific task in a
program.
Functions help divide a large
program into smaller parts and allow the same code to be used multiple times.
They help programmers reduce code repetition and make programs easier to
develop, test, and maintain.
Functions make programs easy to understand , easy to modify ,
less repetitive and more organized
Advantages of Functions
- Code
Reusability:
Functions allow the same code to be used multiple times in a program.
- Modularity: Functions divide a large
program into smaller, manageable parts.
- Improves
Readability:
Functions make the program easier to read and understand.
- Reduces
Repetition:
Functions avoid writing the same code again and again.
- Easy
Maintenance:
Functions make debugging and updating the program easier.
Types of Python Functions
Python functions are mainly divided
into two types:
1. Built-in Functions
Built-in functions are predefined
functions provided by Python that can be used directly without creating them. They are automatically available when the
Python interpreter starts.
Examples:
print( ), int( ), len( ), sum( )
These functions help perform common
tasks without writing extra code
2. User Defined Functions
A user-defined function is a
function created by the programmer to perform a specific task according to the
requirement of the program. A user-defined function is created using the
keyword def.
Example:
def
add(a, b):
return a + b
These functions help in making
programs more organized and reusable
User Defined Function – Definition,
Syntax and Rules
A user-defined
function is a function created by the programmer to perform a specific task
according to the requirement of the program. It allows the programmer to create
their own functions instead of only using Python's built-in functions.
User-defined functions improve code
reusability, program organization, and readability because the same
function can be called multiple times whenever required.
Creating a User Defined Function
In Python, a user-defined function
is created using the keyword def.
Syntax:
def function_name([parameter1,
parameter2, …]):
set of instructions to be executed
[return value]
Explanation:
- The
items written inside [ ] are called parameters and they are
optional.
- A
function may have parameters or may not have parameters.
- A
function may return a value or may not return a value.
- The
function header always ends with a colon (:).
- The
function name should be unique. The rules for naming identifiers
also apply to function names.
- The
statements inside the function must have proper indentation.
Statements outside the function indentation are not considered part of the
function.
Example of User Defined Function
def add_numbers(x, y):
sum = x + y
return sum
num1 = 5
num2 = 6
print(“The sum is”,
add_numbers(num1, num2))
Output:
The sum is 11
Scope of Function
The scope of a user-defined
function refers to the specific area of a program where the function and
its variables can be accessed and used.
In simple words, scope
determines where a variable or function is available in a program.
Variables created inside a function
usually have a limited scope, meaning they can only be used within that
function. They cannot be accessed from outside the function.
Python mainly has two types of
variable scope:
1. Local Scope
Local scope refers to variables that are declared
inside a function.
- These
variables are accessible only within that function.
- They
are created when the function starts and removed when the function ends.
- They
cannot be used outside the function.
Example:
def add():
x = 10
y = 20
print(x + y)
add()
Output:
30
Here, x and y are local variables
because they are declared inside the add() function.
Trying to access them outside the
function:
print(x)
will produce an error because x
exists only inside the function.
2. Global Scope
Global scope refers to variables that are declared
outside any function.
- Global
variables can be accessed from anywhere in the program.
- They
can be used inside functions as well as outside functions.
Example:
x = 100
def show():
print(x)
show()
print(x)
Output:
100
100
Here, x is a global variable
because it is declared outside the function.
Difference Between Local and Global
Scope
|
Local Scope |
Global Scope |
|
Declared inside a function |
Declared outside all functions |
|
Accessible only inside that
function |
Accessible throughout the program |
|
Exists temporarily during
function execution |
Exists until the program ends |
|
Example: variables inside def
block |
Example: variables at program
level |
Conclusion
The scope of a user-defined
function defines where the function and its variables can be accessed. In
Python, variables inside functions have local scope, while variables
declared outside functions have global scope. Understanding scope helps
prevent errors and makes programs easier to organize and maintain.
Function Returns a Value in Python
A function that returns a value
is a function that performs a calculation or task and sends the result back to
the calling function or the Python interpreter using the return
statement.
Syntax of Function Returning a
Value
def function_name(arguments):
return value
Explanation:
- def → Keyword used to define a
function.
- function_name → Name of the function.
- arguments → Input values passed to the
function.
- return → Keyword used to send a
value back.
- value → Result returned by the
function.
# Function to calculate area of
rectangle
def area(length, width):
return length * width
length = 5
width = 8
result = area(length, width)
print("Area of
Rectangle:")
print(result)
Explanation:
- area()
is a user-defined function.
- It
takes two parameters: length and width.
- The
function calculates:
- return
length * width sends the calculated area back to the main program.
- The
returned value is stored in the variable result.
- Finally,
print(result) displays the output.
A function with a return value is
used when we need the result of a calculation or operation for further
processing. The return statement transfers the output from the function back
to the calling program.
Important Points About Return
Statement:
A function can return any type of
value: Integer , Float , String , List , Other objects
Example:
def square(n):
return n * n
x = square(5)
print(x)
Output:
25
Parameters and Arguments in Function
Parameters
Parameters are the values or variables
written inside the parentheses of a function definition. They receive the input
values that are passed to the function when it is called.
Parameters allow a function to work
with different types of input data instead of using fixed values.
Syntax:
def function_name(parameter1,
parameter2):
statements
#
Function to calculate the area of a circle
def area_of_circle(Radius):
area = Radius ** 2 * 22/7
return area
Radius = float(input("Please enter the radius of the given circle:
"))
print("The area of the given circle is:", area_of_circle(Radius))
Here,
Radius in the function definition is a parameter.
Arguments
Arguments are the actual values passed to a
function when the function is called. These values are used by the parameters
to perform the required operation.
Syntax:
function_name(value1, value2)
Example:
add(10, 20)
Here: 10 and 20 are arguments.
Difference Between Parameters and
Arguments
|
Parameters |
Arguments |
|
Parameters are variables written
in the function definition. |
Arguments are actual values
passed during function calling. |
|
They receive values from
arguments. |
They provide values to
parameters. |
|
They are written when creating a
function. |
They are written when calling a
function. |
Example of Parameters and Arguments
def multiply(x, y):
result = x * y
print(result)
multiply(5, 4)
Output:
20
Explanation:
- x
and y are parameters because they are written in the function definition.
- 5
and 4 are arguments because they are passed during function calling.
- The
function multiplies the two values and displays the result.
Scope of Variables
The scope of a
variable refers to the area of a program where a variable can be accessed
and used.
In Python, variables inside and
outside functions have different scopes. The scope determines where a variable
is available and where it can be used during program execution.
Python mainly has two types of
variable scope:
- Local
Scope
- Global
Scope
1. Local Scope
A variable declared inside a
function is called a local variable.
A local variable can be accessed
only within that particular function and cannot be used outside the function.
Example:
def show():
x = 10 # local variable
print(x)
show()
Output:
10
Explanation:
- x
is created inside the function show().
- It
can only be used inside the show() function.
- It
cannot be accessed outside the function.
2. Global Scope
A variable declared outside all
functions is called a global variable.
A global variable can be accessed
from anywhere in the program, including inside functions.
Example:
x = 20 # global variable
def display():
print(x)
display()
Output:
20
Explanation:
- x
is created outside the function.
- It
can be accessed inside the function and other parts of the program.
Difference Between Local and Global
Variables
|
Local Variable |
Global Variable |
|
Declared inside a function. |
Declared outside all functions. |
|
Accessible only inside that
function. |
Accessible throughout the
program. |
|
Created when the function
executes. |
Exists throughout program
execution. |
|
Cannot be used outside the
function. |
Can be used inside and outside
functions. |
Example Showing Both Scopes
x = 100 # Global variable
def test():
y = 50 # Local variable
print(x)
print(y)
test()
Output:
100
50
Explanation:
- x
is a global variable, so it can be accessed inside the function.
- y
is a local variable, so it can only be accessed inside the function.
Passing Parameters
Python supports different types of
arguments to pass values to functions.
The main types of arguments are:
- Positional
Arguments (Required arguments)
- Keyword
Arguments
- Default
Arguments
1. Positional Arguments
Arguments passed to a function in
the same order as the parameters in the function definition are called positional
arguments.
The position of the argument is
important because each value is assigned according to its order.
Example:
if a function definition header is like
def
check(a, b, c):
then function calls for this can be:
check(x, y, z) # 3 values (all
variables) passed
check(2, x, y) # 3 values (literal
variables) passed
check(2, 5, 7) # values (all
literals) passed
Here,
three arguments must be passed because the function has three parameters.
2. Keyword (Named) Arguments
Arguments passed by specifying the
parameter name along with its value are called keyword arguments.
In keyword arguments, the order of
values does not matter because the parameter name is mentioned.
Python offers a way of writing
function calls where you can write any argument in any order provided you name
the arguments when calling the function, as shown below:
Example:
interest(prin=2000,
time=2, rate=0.10)
interest(time=2, prin=2600, rate=0.09)
interest(time=2, rate=0.12, prin=2000)
All the above function calls are
valid now, even if the order of arguments does not match the order of
parameters as defined in the function header.
3. Default Arguments
Arguments that have a default value
assigned in the function definition are called default arguments.
If no value is provided during
function calling, the default value is used.
Example:
def
interest(principal, time, rate=0.10):
return principal * time * rate
Here,
0.10 is the default value of rate.
Important
Rules:
✔
Default parameters must be written after required parameters.
Legal
examples:
def
Interest(prin, time, rate=0.10) #legal
def Interest(prin, time=2, rate=0.10)
def Interest(prin=200, time=2, rate=0.10)
Illegal
examples:
def
Interest(prin, time=2, rate) #
Default before required
def Interest(prin=2000, time=2, rate) #
Default before required
Difference Between Types of
Arguments
|
Positional Arguments |
Keyword Arguments |
Default Arguments |
|
Values are passed according to
position. |
Values are passed using parameter
names. |
Values are assigned default
values in function definition. |
|
Order is important. |
Order is not important. |
Used when no argument is
provided. |
|
Example: add(5,10) |
Example: add(a=5,b=10) |
Example: def add(a=5) |
Return Value in Function
A return value
is the value that a function sends back to the calling program after completing
its task. A function uses the return statement to provide a result to
the place where it was called.
A function may or may not return a
value depending on the requirement of the program.
Return Statement
The return statement in
Python is used to send a value from a function back to the calling program. It
stops the execution of the function and returns the specified value.
Syntax:
def function_name(parameters):
statements
return value
Function with Return Value
(non-void function)
The functions that return some
computed result in terms of a value, fall in this category. The computed value
is returned using return statement as per syntax return
The
returned value can be:
- A
literal
- A
variable
- An
expression
Example:
def
sum(x, y):
s = x + y
return s
result = sum(5, 3)
print(result)
Here,
the returned value replaces the function call.
Function Without Return Value (void
function)
The functions that
perform some action or do some work but do not return any computed value or
final value to the caller are called void functions. A void function may or may
not a return statement. If a void function has a return statement, then, it takes
the following form:
Return
That is,
keyword return without any value or expression.
Following
are some examples of void function:
def
greet():
print("Hello")
greet()
Output:
Hello
This
function only displays a message and does not return any value.
Example
2: Void function with parameter
def
greet1(name):
print("Hello", name)
greet1("Ram")
Output:
Hello Ram
The
function takes a value as an argument but does not return anything.
Example
3: Using return without value
def
quote():
print("Python is good")
return
quote()
Output:
Python is
good
Here,
return only ends the function execution. It does not send any value back.
Example
4: Void function with multiple parameters
def
printsum(a, b, c):
print("Sum is", a + b + c)
return
printsum(10,
20, 30)
Output:
Sum is 60
The
function calculates and displays the result but does not return it.
Important
Points:
- Void
functions perform an action but do not give back a result.
- They
are mainly used for:
- Printing
output
- Displaying
messages
- Changing
data
- Performing
tasks
- If
we try to store the result of a void function:
x =
greet()
print(x)
Output:
Hello
None
Because
Python automatically returns None.
The void
functions do not return a value, but, they return a legal empty value of python.
Example:
def display():
print("Hello Python")
display()
Output:
Hello Python
Here, the function only displays
output and does not return any value.
Difference Between Print and Return
|
print() |
return |
|
Displays output on the screen. |
Sends value back to the calling
program. |
|
Cannot be stored for later use. |
Returned value can be stored and
reused. |
|
Mainly used for displaying
results. |
Used when a function needs to
provide a result. |
Returning Multiple Values
A function in Python can return more
than one value using a single return statement. Multiple values are
separated by commas.
Syntax:
def function_name(parameters):
statements
return value1, value2, value3
Explanation:
- A
function can return multiple values at the same time.
- The
values returned by the function are separated by commas.
- The
returned values can be stored in a single variable or in multiple
variables.
Example 1: Storing Multiple Values
in One Variable
def squared(x, y, z):
return x*x, y*y, z*z
t = squared(2, 5, 7)
print(t)
Example 2: Storing Returned Values
in Multiple Variables
def squared(x, y, z):
return x*x, y*y, z*z
v1, v2, v3 = squared(2, 3, 4)
print("The returned values are
as under:")
print(v1, v2, v3)
Note:
A function can return any number of values, but the number of variables
receiving the values should match the number of returned values.
Practical Programs Based on User
Defined Functions
Program 1: Write a Python program
to add two numbers using a user-defined function.
Program:
def add_numbers(a, b):
result = a + b
return result
num1 = int(input("Enter first
number: "))
num2 = int(input("Enter second
number: "))
sum = add_numbers(num1, num2)
print("Sum =", sum)
Program 2: Write a Python program
to find the area of a rectangle using a user-defined function.
Formula:
Program:
def area_rectangle(length,
breadth):
area = length * breadth
return area
l = float(input("Enter length:
"))
b = float(input("Enter
breadth: "))
result = area_rectangle(l, b)
print("Area of rectangle
=", result)
Program 3: Write a Python program
to find the square of a number using a user-defined function.
Program:
def square(num):
return num * num
n = int(input("Enter a number:
"))
print("Square =",
square(n))
Program 4: Write a Python program
to check whether a number is even or odd using a user-defined function.
Program:
def check_even_odd(num):
if num % 2 == 0:
return "Even"
else:
return "Odd"
n = int(input("Enter a number:
"))
print(check_even_odd(n))
Program 5: Write a Python program
to calculate factorial using a user-defined function.
Program:
def factorial(n):
fact = 1
for i in range(1, n+1):
fact = fact * i
return fact
num = int(input("Enter a
number: "))
print("Factorial =",
factorial(num))
Program 6: Write a Python program
to find the greatest among two numbers using a user-defined function.
Program:
def greatest(a, b):
if a > b:
return a
else:
return b
x = int(input("Enter first
number: "))
y = int(input("Enter second
number: "))
print("Greatest number
=", greatest(x, y))
MCQ
1.
Which keyword is used to define a user-defined function in Python?
a) function b) define c) def d) func
2. What are the values passed to a function when it is called known as?
a) Parameters b) Arguments c) Return values d) Scope
3. The part of the program where a function can be accessed is called its:
a) Parameter b) Argument c) Return type d) Scope
4. Variables declared inside a function have:
a) Global scope b) Local scope c) Unlimited scope d) No scope
5. What does the return statement do in a Python function?
a) Prints output to the console b)
Takes input from the user
c)
Sends a value back to the caller d) Defines the function
6. What are the values specified in the function header within the
parentheses called?
a) Arguments b) Parameters c) Return values d) Local variables
Answer: b) Parameters
7.
What type of argument allows you to call a function by specifying parameter
names?
a) Positional arguments b) Default arguments c) Keyword arguments d)
Required arguments
8. A function that performs an action but does not explicitly return a value
is called a:
a) Non-void function b) Void function c) Recursive function d)
Anonymous function
9. Can a Python function return multiple values?
a) No b) Yes, as a list c) Yes, as a tuple d) Yes, directly separated by
commas
Short
Questions
1.
What is the main benefit of using user-defined functions in programming?
Answer: The main benefit of using
user-defined functions is code reusability, as they allow a block of
code to be written once and used multiple times in a program.
2.
Name the two types of Python functions.
Answer: The two types of Python functions
are:
- Built-in
functions
- User-defined
functions
3.
Explain the difference between a parameter and an argument in the context of
Python functions.
Answer:
A parameter is a variable listed in the function definition that
receives a value when the function is called.
An argument is the actual value that is passed to the function during
the function call.
Example:
def
add(x, y): # x and y are parameters
return x + y
add(5, 3) # 5 and 3 are arguments
Here,
x and y are parameters, while 5 and 3 are arguments.
4.
What is local scope in Python functions? Provide a brief example.
Answer:
Local scope refers
to variables that are declared inside a function and can be accessed only
within that function. These variables exist only while the function is
executing.
Example:
def
display( ):
x = 10 # Local variable
print(x)
display( )
In
this example, x is a local variable and cannot be accessed outside the display(
) function.
5.
What is global scope in Python? How does it differ from local scope?
Answer:
Global scope
refers to variables that are declared outside all functions and can be accessed
from anywhere in the program.
It
differs from local scope because local variables are declared inside a function
and can only be accessed within that function.
Example:
x
= 20 # Global variable
def show( ):
y = 10 # Local variable
print(x) # Accessing global variable
print(y)
show( )
Here,
x has global scope and can be used inside the function, while y has local scope
and cannot be accessed outside the function.
6.
What is the purpose of the return keyword in a Python function?
Answer:
The return keyword
is used to send a value back to the calling function. It ends the execution of
the function and returns the specified result to where the function was called.
Example:
def
add(a, b):
return a + b
result = add(4, 6)
print(result)
Here,
return a + b sends the calculated value back to the caller.
7.
Explain what positional arguments are and how they are passed to a function.
Answer:
Positional
arguments are the arguments that are passed to a function in the same order as
the parameters defined in the function. The position of each argument
determines which parameter it is assigned to.
The
number of arguments and their order must match the function definition.
Example:
def
display(a, b, c):
print(a, b, c)
display(1, 2, 3)
Here,
1 is assigned to a, 2 to b, and 3 to c based on their positions.
8.
Describe the use case for default arguments in Python functions.
Answer:
Default arguments
are used when a function parameter has a predefined value. They are helpful
when a common or standard value is usually used, so the user does not need to
provide that value every time the function is called.
If
no argument is passed for that parameter, the default value is automatically
used.
Example:
def
interest(principal, time, rate=0.10):
return principal * time * rate
print(interest(1000, 2)) # Uses
default rate
print(interest(1000, 2, 0.12)) # Uses
given rate
Here,
rate has a default value of 0.10, which is used if no rate is provided.
9.
What are keyword arguments, and what advantage do they offer when calling a
function?
Answer:
Keyword arguments are arguments passed to a function by specifying the
parameter names along with their values during the function call.
The
main advantage of keyword arguments is that they allow the arguments to be
passed in any order, as long as the parameter names are correctly specified.
This improves readability and reduces errors.
Example:
def
interest(principal, time, rate):
return principal * time * rate
print(interest(time=2, rate=0.10, principal=1000))
Here,
the arguments are passed in a different order, but because parameter names are
specified, the function works correctly.
10.
What happens if a void function has a return statement without any value?
Answer:
If a void function
has a return statement without any value, it simply ends the execution of the
function and returns a special value called None to the caller.
The
return keyword without a value does not send any computed result; it only exits
the function.
Example:
def
greet( ):
print("Hello")
return
result = greet( )
print(result)
Output:
Hello
None
Here,
the function prints “Hello” and then returns None because no value is specified
after return.
Long
Questions
1.
Explain the concept of function scope in Python, differentiating between local
and global scope.
Answer:
Function
scope in Python refers to the region of a program where a variable can be
accessed. It determines the visibility and lifetime of variables within a
program.
There
are two main types of scope in Python:
Local
Scope
A
variable declared inside a function is said to have local scope.
It can be accessed only within that function and exists only while the function
is executing.
Example:
def
show():
x = 10 # Local variable
print(x)
show( )
Here,
x is a local variable and cannot be accessed outside the function.
Global
Scope
A
variable declared outside all functions has global scope.
It can be accessed from anywhere in the program, including inside functions.
Example:
x
= 20 # Global variable
def display( ):
print(x)
display( )
Here,
x is a global variable and can be used inside the function.
Difference:
Local variables are accessible only within the function in which they are
defined, whereas global variables can be accessed throughout the entire
program.
2.
Describe the concept of return values in Python functions. Differentiate
between functions that return a value (non-void) and those that do not (void).
Provide examples of both types and explain how the return value can be used in
the calling part of the program.
Answer:
In
Python, a function may return a value to the caller using the return statement.
The value returned can be used in the calling part of the program for further
processing, calculation, or display.
There
are two types of functions based on return values:
Non-void
Functions (Functions Returning a Value)
Non-void
functions return a computed result using the return statement.
Example:
def
add(a, b):
return a + b
result = add(5, 3)
print("Sum is:", result)
Here,
the function returns the sum of a and b.
The returned value replaces the function call and is stored in the variable
result, which is then printed.
Use: The returned value can be assigned
to a variable, used in expressions, or passed to another function.
Void
Functions (Functions Not Returning a Value)
Void
functions perform an action but do not return any value.
If no return statement is used, Python automatically returns None.
Example:
def
greet():
print("Hello")
greet()
This
function prints a message but does not return any value.
If
written as:
def
greet():
print("Hello")
return
It
still does not return any specific value.
Difference
Between Non-void and Void Functions
|
Non-void Function |
Void Function |
|
Returns a value using return |
Does not return any value |
|
Can be used in expressions |
Used mainly to perform actions |
|
Replaces function call with
returned value |
Returns None by default |
In
conclusion, return values allow functions to send computed results back to the
caller, making programs more flexible and powerful.
3.
Python allows functions to return multiple values. Explain how this is achieved
and provide an example demonstrating a function that returns multiple values
and how these values can be accessed by the caller.
Answer:
Python
allows a function to return multiple values by separating them with commas in
the return statement.
When multiple values are returned, Python automatically packs them into a
tuple.
The
caller can access these values either by storing them in a single variable (as
a tuple) or by unpacking them into multiple variables.
Example:
def
calculate(a, b):
sum = a + b
product = a * b
return sum, product
result = calculate(4, 5)
print(result)
Output:
(9,
20)
Here,
the returned values are stored as a tuple in result.
Accessing
Values Using Unpacking:
def
calculate(a, b):
sum = a + b
product = a * b
return sum, product
s, p = calculate(4, 5)
print("Sum:", s)
print("Product:", p)
Output:
Sum:
9
Product: 20
In
this case, the returned values are unpacked into variables s and p.
Thus,
multiple values are returned using a single return statement separated by
commas, and they can be accessed either as a tuple or through variable
unpacking.
4.
Design a Python program that includes at least two user-defined functions:
i.
One function that takes two numbers as arguments and returns their product.
ii. Another function that takes a list of numbers as an argument and prints
each number.
#
Function that takes two numbers as arguments and returns their product
def multiply(a, b):
return a * b
# Function that takes a list of numbers and prints each number
def print_numbers(num_list):
for num in num_list:
print(num)
# Calling the first function
product_result = multiply(6, 7)
print("Product of two numbers:", product_result)
# Calling the second function
numbers = [1, 2, 3, 4, 5]
print("Elements in the list:")
print_numbers(numbers)
Output:
Product
of two numbers: 42
Elements in the list:
1
2
3
4
5
4.3 Concept of Library and Packages
in Python
1. Python Module
A module in Python is a file
that contains Python code, such as functions, variables, classes, and
statements, which can be reused in other Python programs.
A module is usually stored as a Python
file (.py) and can be imported into another program using the import
statement.
Modules help programmers organize
code, avoid repetition, and reuse existing code.
Creating a Module
Example: Create a file named calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
Here, calculator.py is a module
because it contains Python functions.
Using a Module
We can use the module in another
program by using the import statement.
Example:
import calculator
result = calculator.add(5, 3)
print(result)
Output:
8
Explanation:
- import
calculator loads the module.
- calculator.add()
calls the add() function from that module.
Types of Modules in Python
Python modules are mainly divided
into two types:
1. Built-in Modules
These are modules that are already
available in Python. We do not need to create them.
Examples:
Math Module
import math
print(math.sqrt(25))
Output:
5.0
Other built-in modules:
- random
→ generates random numbers
- datetime
→ works with date and time
- os
→ interacts with the operating system
2. User-defined Modules
Modules created by programmers
themselves are called user-defined modules.
Example:
student.py
name = "Ram"
def display():
print("Student Information")
Using the module:
import student
print(student.name)
student.display()
Advantages of Modules
- Code
Reusability –
Same code can be used multiple times.
- Easy
Maintenance –
Large programs can be divided into smaller files.
- Avoids
Code Repetition
– Functions can be written once and reused.
- Improves
Program Organization
– Makes programs easier to understand.
- Saves
Development Time
– Existing modules can be imported and used.
|
Function |
Module |
|
A function is a block of
code that performs a specific task. |
A module is a file that
contains Python code (functions, variables, classes, etc.). |
|
It is used to perform a
particular operation. |
It is used to organize and reuse
a collection of code. |
|
A function is written using the
def keyword. |
A module is a Python file with a
.py extension. |
|
A module can contain many
functions. |
A module can contain functions,
variables, and classes. |
|
Example: add() function |
Example: math module or
calculator.py module |
2. Python Library
A Python library is a
collection of multiple modules and packages that together provide
solutions for a specific type of application or requirement. Libraries contain
pre-written code that helps programmers perform complex tasks easily without
writing everything from scratch.
Python libraries improve code
reusability, reduce programming effort, and make software development
faster and more efficient.
Commonly Used Python Libraries:
1. NumPy (Numerical Python)
- NumPy
is a scientific computing library.
- It
supports large arrays and provides various mathematical functions.
- It
is used for numerical calculations and data processing.
Examples of uses:
- Array
operations
- Matrix
calculations
- Scientific
computations
2. Pandas
- Pandas
is a library used for data manipulation and analysis.
- It
provides tools for handling and analyzing different types of data.
Examples of uses:
- Data
organization
- Data
cleaning
- Data
analysis
3. Matplotlib
- Matplotlib
is a library used for creating graphs and charts.
- It
helps in data visualization through static and interactive graphs.
- It
is commonly used with Pandas.
Examples of uses:
- Bar
charts
- Line
graphs
- Data
visualization
Advantages of Python Libraries:
- Provides
ready-made functions and tools.
- Saves
programming time and effort.
- Improves
code reusability.
- Helps
solve complex problems easily.
- Makes
program development more efficient.
3. Python Package
A Python package is a
collection of related modules stored together in a directory (folder)
that is used to perform specific tasks. Packages help organize Python programs,
improve code management, and ensure code reusability.
A package can contain multiple
modules, functions, and sub-packages. To use a module from a package, we use
the import statement in a Python program.
Syntax:
import package_name.module_name
Example:
The math package contains
various mathematical functions such as sqrt() for finding the square root of a
number.
import math
print(math.sqrt(25))
Output:
5.0
Advantages of Python Packages:
- Helps
organize large programs into smaller parts.
- Promotes
code reuse.
- Makes
program development easier and faster.
- Reduces
code duplication.
- Improves
program readability and maintenance.
Difference Between Module, Package
and Library
|
Basis |
Module |
Package |
Library |
|
Definition |
A module is a single Python file
containing functions, variables, and statements that perform specific tasks. |
A package is a collection of
related modules organized together in a folder to perform specific tasks. |
A library is a collection of
multiple packages and modules that provides solutions for specific
applications or requirements. |
|
Purpose |
Used to divide a program into
smaller, reusable units. |
Used to organize and manage
multiple related modules. |
Used to provide ready-made tools
and functions for complex applications. |
|
Size |
Smallest unit among the three. |
Larger than a module but smaller
than a library. |
Largest collection containing
packages and modules. |
|
Contains |
Functions, classes, variables,
and code statements. |
Multiple related modules. |
Multiple packages and modules. |
|
Example |
math.py module |
numpy package |
NumPy library, Pandas library |
4.3.1 Importing and Use of Standard
Libraries
A Python library is a
collection of pre-written code and information that provides additional
functionality to the Python programming language. Python comes with a set of standard
libraries that contain built-in modules to perform common tasks such as file
handling, mathematical operations, system operations, date and time operations,
and more.
These libraries can be accessed in
a Python program using the import statement.
Syntax:
import library_name
Example:
import requests
Python provides different ways to
import and use standard libraries:
a. Import the Entire Module
In this method, the complete module
is imported. To access functions, we use:
Syntax:
module_name.function_name()
Example:
import math
print(math.sqrt(25))
Output:
5.0
Here, sqrt() is accessed using the
module name math.
b. Import a Specific Function from
a Module
In this method, only a particular
function is imported from a module. There is no need to write the module name
while calling the function.
Syntax:
from module_name import
function_name
Example:
from math import sqrt
print(sqrt(25))
Output:
5.0
Here, sqrt() can be directly used
without writing math.sqrt().
c. Import a Module with an Alias
(Shortcut)
An alias is a short name given to a
module while importing it. It makes the code shorter and easier to write.
Syntax:
import module_name as alias_name
Example:
import datetime as dt
print(dt.datetime.now())
Output:
Current date and time
Here, dt is used as a shortcut for
the datetime module.
d. Import All Functions from a
Module
In this method, all functions from
a module are imported. The functions can be used directly without writing the
module name.
Syntax:
from module_name import *
Example:
from math import *
print(sin(90))
Output:
0.8939966636005579
(Note: The output is based on
radians because Python's mathematical functions use radians by default.)
Advantages of Importing Standard
Libraries:
- Provides
ready-made functions and modules.
- Saves
programming time and effort.
- Reduces
the need to write complex code.
- Improves
code reusability.
- Makes
program development easier.
Key Point ⭐
Import statement is used to include
Python libraries or modules in a program so that their functions can be used.
4.3.2 Introduction to Popular
Python Libraries
(Math, Random, Pandas, Turtle and
Matplotlib)
Python libraries are collections of
pre-written code that help programmers perform common tasks easily. Libraries
are designed to provide ready-made functions, perform complex operations, and
allow code reuse.
Libraries can be imported using the
import statement.
Syntax:
import library_name
Some popular Python libraries are:
1. Math Library
The Math library is a
built-in Python library that provides access to various mathematical
functions and constants. It is used to perform mathematical operations that
are not directly available in basic Python.
The Math library includes functions
for:
- Basic
mathematical calculations
- Trigonometric
operations
- Logarithmic
calculations
- Power
operations
- Mathematical
constants
Syntax:
import math
Important Functions of Math
Library:
i. Mathematical Constants
- math.pi
→ Returns the value of π (3.14159...)
ii. Trigonometric Functions
- sin()
→ Calculates sine value
- cos()
→ Calculates cosine value
- tan()
→ Calculates tangent value
iii. Logarithmic Functions
- log()
→ Calculates natural logarithm
- log10()
→ Calculates base-10 logarithm
iv. Power Functions
- pow()
→ Calculates power of a number
- sqrt()
→ Calculates square root of a number
Example:
import math
# Compute the square root of 256
x = math.sqrt(256)
print("Square root is ",
math.sqrt(16))
print("Value is ",
math.sin(math.pi/2))
print("Code works just fine, x
is equal to ", x)
Output:
Square root is 4.0
Value is 1.0
Code works just fine, x is equal to
16.0
Advantages of Math Library:
- Provides
ready-made mathematical functions.
- Reduces
the need to write complex mathematical code.
- Makes
mathematical calculations easier and faster.
- Improves
code reusability.
- Supports
advanced mathematical operations.
2. Random Library
The Random library is a
built-in Python library used to generate random numbers and perform random
selections. It is commonly used in applications such as games,
simulations, random sampling, and security-related programs.
The Random library provides
different functions for generating random values according to the required
condition.
Syntax:
import random
Important Functions of Random
Library:
i. randrange()
- Returns
a random number within a specified range.
Example:
random.randrange(1, 10)
ii. randint()
- Returns
a random integer between two given numbers.
Example:
random.randint(1, 10)
Output:
7
iii. choice()
- Returns
a random item from a list, tuple, or string.
Example:
random.choice(['Apple', 'Banana',
'Orange'])
Output:
Banana
iv. random()
- Generates
a random floating-point number between 0 and 1.
Example:
random.random()
Output:
0.654321
Example Program:
import random
print(random.randint(1, 10))
print(random.choice(['Apple',
'Banana', 'Orange']))
list1 = [1, 2, 3, 4, 5, 6]
print(random.choice(list1))
Output:
8
Apple
4
Another Example:
import random
r1 = random.randint(5, 15)
print("Random number between 5
and 15 is %s" % (r1))
r2 = random.randint(-10, -2)
print("Random number between
-10 and -2 is %d" % (r2))
Output:
Random number between 5 and 15 is
12
Random number between -10 and -2 is
-6
Applications of Random Library:
- Generating
random numbers.
- Creating
games and simulations.
- Selecting
random samples from data.
- Generating
random passwords and security codes.
3. Pandas Library
The Pandas library is a
Python library used for data manipulation, analysis, and management. It
provides powerful data structures and functions to work with large datasets
easily.
Pandas is mainly used for handling numerical
tables and time series data. It also supports reading and writing data from
different file formats such as CSV, Excel, and SQL.
Pandas helps programmers to
organize, clean, process, and analyze data efficiently.
Installation:
Before using Pandas, it can be
installed using the pip command:
pip install pandas
Syntax:
import pandas as pd
Here, pd is an alias (short name)
used for the Pandas library.
Important Functions of Pandas
Library:
|
Function |
Description |
|
pandas.read_csv() |
Loads data from a CSV file into a
table-like structure called DataFrame. |
|
DataFrame.info() |
Displays information about
DataFrame such as column names, data types, and missing values. |
|
DataFrame.shape |
Returns the size of DataFrame in
the form of (rows, columns). |
|
pandas.DataFrame() |
Creates a DataFrame containing
rows and columns for storing data. |
Important Concept: DataFrame
A DataFrame is a
two-dimensional table-like data structure in Pandas that stores data in rows
and columns.
Example:
|
Name |
Age |
|
Shyam |
25 |
|
Sanskar |
30 |
Example Program:
import pandas as pd
data = {
'Name': ['Shyam', 'Sanskar'],
'Age': [25, 30]
}
df = pd.DataFrame(data)
print(df)
Output:
Name
Age
0 Shyam
25
1
Sanskar 30
Applications of Pandas:
- Data
analysis and processing.
- Managing
large datasets.
- Cleaning
and organizing data.
- Reading
and writing data files.
- Performing
statistical calculations.
Advantages of Pandas:
- Easy
handling of structured data.
- Provides
fast data processing tools.
- Supports
multiple file formats.
- Reduces
complexity in data analysis.
- Provides
reusable functions for data management.
4. Turtle Library
The Turtle library is a
built-in Python module used to create graphics, drawings, shapes, and
animations on the screen. It uses a cursor called a turtle that
moves around the screen and draws according to the given commands.
Turtle provides a simple and
interactive way to learn programming by creating visual designs and graphical
representations.
Syntax:
import turtle
Important Functions of Turtle
Library:
|
Function |
Description |
|
forward() |
Moves the turtle forward by a
specified distance. |
|
backward() |
Moves the turtle backward by a
specified distance. |
|
right() |
Turns the turtle clockwise by a
specified angle. |
|
left() |
Turns the turtle counterclockwise
by a specified angle. |
|
goto() |
Moves the turtle to a specified
position. |
|
pendown() |
Places the turtle’s tail down so
it draws while moving. |
|
penup() |
Lifts the turtle’s tail so it
stops drawing. |
|
Turtle() |
Creates and returns a new turtle
object. |
|
mainloop() |
Keeps the drawing window open and
waits for user actions. |
Example Program:
import turtle
s = turtle.Turtle()
for i in range(4):
s.forward(50)
s.right(90)
turtle.done()
Output:
A square shape is drawn on
the screen.
Applications of Turtle Library:
- Creating
different shapes and patterns.
- Designing
simple animations.
- Learning
programming concepts through graphics.
- Creating
educational drawings and visual projects.
Advantages of Turtle Library:
- Easy
for beginners to learn programming.
- Provides
a visual way to understand coding.
- Helps
develop logical thinking and creativity.
- Makes
programming interactive and interesting.
5. Matplotlib Library
The Matplotlib library is a
Python library used for creating high-quality graphs, charts, and data
visualizations. It provides tools to represent data in a graphical form,
making it easier to understand and analyze.
Matplotlib is an open-source
library created by John D. Hunter. It can be used freely and
supports different types of visualizations, including 2D and 3D plots.
Before using Matplotlib, it can be
installed using the pip command:
Installation:
pip install matplotlib
Syntax:
import matplotlib.pyplot as plt
Here, plt is an alias (short name)
used for the Matplotlib plotting module.
Types of Plots in Matplotlib:
i. Line Plot
- A
line plot shows the relationship between values on the x-axis and
y-axis.
- It
is mainly used to show trends and changes over time.
Example:
plt.plot(x, y)
ii. Bar Plot
- A
bar plot represents the relationship between numerical values and
categorical data.
- It
is used for comparing different categories.
Example:
plt.bar(x, y)
iii. Pie Chart
- A
pie chart (circular chart) represents the percentage or proportion of a
whole.
- It
is useful for showing distribution of data.
Example:
plt.pie(values)
Example Program:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [10, 20, 30, 40]
plt.plot(x, y)
plt.show()
Output:
A line graph is displayed on the
screen.
Applications of Matplotlib:
- Creating
graphs and charts.
- Visualizing
large amounts of data.
- Representing
statistical information.
- Analyzing
trends and patterns.
- Creating
reports using graphical data.
Advantages of Matplotlib:
- Creates
high-quality visualizations.
- Supports
different types of graphs.
- Easy
integration with Pandas and NumPy.
- Supports
2D and 3D plotting.
- Helps
understand complex data easily.
4.4 Graphics Using Turtle
Definition of Turtle Module
The Turtle module is a
pre-built Python module used to create graphics, shapes, figures, and
designs on the screen using a cursor called a turtle.
The turtle moves according to the
commands given by the programmer and draws lines and shapes. It is mainly used
for learning programming concepts through interactive graphics.
Syntax:
import turtle
Drawing Turtle
To create a turtle object, we use
the Turtle() function.
Syntax:
turtle.Turtle()
Example:
import turtle
t = turtle.Turtle()
t.forward(100)
turtle.done()
Here, t is the turtle object that
moves and draws on the screen.
Important Turtle Functions
|
Function |
Parameter |
Description |
|
forward() |
amount |
Moves the turtle forward by the
specified distance. |
|
backward() |
amount |
Moves the turtle backward by the
specified distance. |
|
right() |
angle |
Turns the turtle clockwise by the
specified angle. |
|
left() |
angle |
Turns the turtle counterclockwise
by the specified angle. |
|
penup() |
None |
Lifts the turtle's pen so it
stops drawing. |
|
color() |
Color name |
Changes the color of the turtle's
pen. |
|
fillcolor() |
Color name |
Changes the color used to fill a
polygon. |
|
shape() |
Shape name |
Changes the appearance of the
turtle cursor. |
Uses of Turtle Module
i. Easy Visualization of
Programming Concepts
- Helps
understand loops, functions, and variables through graphics.
- Makes
programming concepts more interesting.
ii. Interactive Learning
- Users
can control turtle movements and create different shapes using Python
commands.
iii. Enhances Creativity
- Beginners
can create attractive patterns, designs, and drawings using simple code.
iv. Simplified Debugging
- Python
is a high-level language, making programs easier to understand and debug
compared to low-level graphics programming.
Turtle Motion and Important Turtle
Functions
The Turtle module provides
various functions to control the movement, direction, color, and appearance of
the turtle. The turtle can move forward and backward in the direction it is
facing.
1. forward(distance) /
turtle.fd(distance)
The forward() function moves
the turtle in the forward direction by a specified distance.
- It
takes one parameter: distance
- Distance
can be an integer or floating-point value.
Syntax:
turtle.forward(distance)
Example:
import turtle
sk = turtle.Turtle()
sk.forward(50)
turtle.done()
Output:
The turtle moves 50 units forward.
2. backward(distance) /
turtle.bk(distance) / turtle.back(distance)
The backward() function
moves the turtle in the opposite direction from where it is facing.
- It
does not change the turtle's heading (direction).
Syntax:
turtle.backward(distance)
Example:
import turtle
sk = turtle.Turtle()
sk.backward(50)
turtle.mainloop()
Output:
The turtle moves 50 units backward.
3. right(angle) / turtle.rt(angle)
The right() function turns
the turtle clockwise by the specified angle.
Syntax:
turtle.right(angle)
Example:
import turtle
t = turtle.Turtle()
t.heading()
t.right(30)
t.heading()
turtle.mainloop()
Output:
The turtle turns 30 degrees to the right.
4. left(angle) / turtle.lt(angle)
The left() function turns
the turtle counterclockwise by the specified angle.
Syntax:
turtle.left(angle)
Example:
import turtle
t = turtle.Turtle()
t.heading()
t.left(100)
t.heading()
turtle.mainloop()
Output:
The turtle turns 100 degrees to the left.
5. penup()
The penup() function lifts
the turtle's pen from the digital canvas. When the turtle moves in the penup
state, it does not draw anything.
Syntax:
turtle.penup()
Example:
import turtle
turtle.color("red")
turtle.speed(1)
turtle.left(90)
for i in range(4):
turtle.forward(30)
turtle.penup()
turtle.forward(30)
turtle.pendown()
turtle.exitonclick()
Output:
The turtle moves without drawing during the penup state.
6. color()
The color() function is used
to change the color of the turtle's drawing pen.
- The
default drawing color is black.
Syntax:
turtle.color(color_name)
Example:
import turtle
turtle.forward(50)
turtle.color("blue")
turtle.forward(150)
turtle.color("red")
turtle.forward(50)
Output:
The turtle draws lines in different colors.
7. fillcolor()
The fillcolor() function is
used to select the color for filling a closed shape.
It accepts:
- Color
name (e.g., "red", "blue")
- Hexadecimal
color value (e.g., #RRGGBB)
To fill shapes, we use:
a) begin_fill()
- Starts
filling the upcoming closed shape.
b) end_fill()
- Stops
filling the closed shape.
Syntax:
turtle.fillcolor(color)
turtle.begin_fill()
turtle.end_fill()
Example:
import turtle
t = turtle.Turtle()
r = int(input("Enter the
radius of the circle: "))
col = input("Enter the color
name: ")
t.fillcolor(col)
t.begin_fill()
t.circle(r)
t.end_fill()
Output:
A circle is drawn and filled with the selected color.
8. shape()
The shape() function is used
to set or return the shape of the turtle cursor.
Syntax:
turtle.shape(name=None)
Available Turtle Shapes:
- "arrow"
- "turtle"
- "circle"
- "square"
- "triangle"
- "classic"
Example:
import turtle
# Default shape
turtle.forward(100)
# Circle shape
turtle.shape("circle")
turtle.right(60)
turtle.forward(100)
# Triangle shape
turtle.shape("triangle")
turtle.right(60)
turtle.forward(100)
# Square shape
turtle.shape("square")
turtle.right(60)
turtle.forward(100)
# Arrow shape
turtle.shape("arrow")
turtle.right(60)
turtle.forward(100)
# Turtle shape
turtle.shape("turtle")
turtle.right(60)
turtle.forward(100)
Output:
The turtle cursor changes into different shapes while drawing.
Key Point:
Turtle functions control the
movement, drawing style, color, and appearance of the turtle to create graphics
and designs in Python.
⭐
1. Draw a Square Using Turtle ⭐
Program:
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(100)
t.right(90)
turtle.done()
2. Draw a Rectangle
Program:
import turtle
t = turtle.Turtle()
for i in range(2):
t.forward(150)
t.right(90)
t.forward(80)
t.right(90)
turtle.done()
3. Draw a Triangle ⭐
Program:
import turtle
t = turtle.Turtle()
for i in range(3):
t.forward(100)
t.right(120)
turtle.done()
4. Draw a Circle
Program:
import turtle
t = turtle.Turtle()
t.circle(50)
turtle.done()
5. Draw a Polygon (User Input
Sides)
Program:
import turtle
t = turtle.Turtle()
sides = int(input("Enter
number of sides: "))
angle = 360 / sides
for i in range(sides):
t.forward(100)
t.right(angle)
turtle.done()
Example:
Input:
6
6. Draw a Star ⭐⭐⭐
Program:
import turtle
t = turtle.Turtle()
for i in range(5):
t.forward(150)
t.right(144)
turtle.done()
7. Draw Colored Square (Fill Color)
⭐
Program:
import turtle
t = turtle.Turtle()
t.fillcolor("yellow")
t.begin_fill()
for i in range(4):
t.forward(100)
t.right(90)
t.end_fill()
turtle.done()
8. Change Turtle Color
Program:
import turtle
t = turtle.Turtle()
t.color("red")
t.forward(100)
t.color("blue")
t.forward(100)
turtle.done()
9. Draw Multiple Shapes Using
Different Turtle Shapes
Program:
import turtle
turtle.forward(100)
turtle.shape("circle")
turtle.forward(100)
turtle.shape("triangle")
turtle.forward(100)
turtle.shape("square")
turtle.forward(100)
turtle.shape("turtle")
turtle.done()
10. Create a Spiral Pattern ⭐
Program:
import turtle
t = turtle.Turtle()
for i in range(50):
t.forward(i * 5)
t.right(45)
turtle.done()
11. Draw a House Using Turtle ⭐⭐⭐
Program:
import turtle
t = turtle.Turtle()
# Square body
for i in range(4):
t.forward(100)
t.right(90)
# Roof
t.left(45)
t.forward(70)
t.right(90)
t.forward(70)
turtle.done()
12. Moving Turtle Without Drawing
(penup & pendown)
Program:
import turtle
t = turtle.Turtle()
t.forward(100)
t.penup()
t.forward(100)
t.pendown()
t.forward(100)
turtle.done()
Concept:
- penup()
→ Stop drawing
- pendown()
→ Start drawing
13. Draw a Colorful Circle
Program:
import turtle
t = turtle.Turtle()
t.fillcolor("green")
t.begin_fill()
t.circle(80)
t.end_fill()
turtle.done()
14. Draw Flower Pattern ⭐
Program:
import turtle
t = turtle.Turtle()
t.speed(5)
for i in range(36):
t.circle(50)
t.right(10)
turtle.done()
4.5 Error handling: errors and
exceptions, try-except blocks
Introduction to Error Handling
Error handling is the process of identifying,
managing, and resolving errors that occur during the execution of a program. It
helps prevent programs from stopping suddenly and improves the reliability,
stability, and maintainability of software.
In Python, error handling is
performed using try, except, else, and finally blocks to handle
exceptions and provide suitable responses when errors occur.
Error handling improves the:
- Reliability
of programs
- Stability
of software
- Maintainability
of code
Python provides different
mechanisms to handle errors and exceptions effectively.
Errors and Exceptions
1. Errors
An error is a problem in a
program that prevents it from completing its task successfully. Errors occur
due to mistakes in code and may stop program execution.
Types of Errors:
i. Syntax Errors
A syntax error is an error
that occurs when a program violates the rules or grammar of the Python
programming language. It happens due to mistakes in writing code, such as
missing colons, incorrect indentation, or incorrect use of keywords.
Examples:
- Missing
colon (:)
- Incorrect
indentation
- Incorrect
use of keywords
Example:
if x > 10
print(x)
Output:
SyntaxError: invalid syntax
ii. Runtime Errors
A runtime error is an error
that occurs during the execution of a program after the code has been
successfully written and interpreted. The program starts running but stops when
it encounters an unexpected problem.
Runtime errors are caused by
problems that cannot be detected before execution.
Common Examples of Runtime Errors:
- Division
by zero
- Invalid
input
- Accessing
an unavailable file
- Using
an undefined variable
Example:
numerator = int(input("Enter
numerator: "))
denominator = int(input("Enter
denominator: "))
result = numerator / denominator
print(result)
Output (if denominator is 0):
ZeroDivisionError: division by zero
In short:
Runtime Error = An error that
occurs while a program is running and prevents it from completing its task. ⭐
iii. Logical Errors
A logical error is an error
that occurs when a program runs successfully without showing any syntax or
runtime errors, but produces an incorrect or unexpected output due to
mistakes in the program logic or algorithm.
Logical errors are usually caused
by:
- Wrong
formulas
- Incorrect
conditions
- Mistakes
in algorithm design
Example:
firstnum = int(input("Enter
first number: "))
secondnum = int(input("Enter
second number: "))
result = (firstnum + secondnum) / 2
print("The result is:",
result)
If the programmer uses an incorrect
formula or calculation, the program executes but gives the wrong answer.
In short:
Logical Error = An error in the
logic of a program that produces incorrect output even though the program runs
successfully. ⭐
2. Exceptions
Exceptions (in Python)
An exception is an error
that occurs during the execution (runtime) of a program, even though the
program statement is syntactically correct.
In other words, the code may be
written correctly according to Python rules, but a problem occurs when Python
tries to execute it. These runtime errors are called exceptions.
Key Points:
- Exceptions
occur during program execution, not while writing the code.
- Exceptions
are not always fatal; they can be handled using Python's built-in
exception-handling mechanisms.
- If
an exception is not handled, Python displays an error message and
stops the program execution.
- Programmers
can write special code to handle specific exceptions and allow the program
to continue running.
Example: Division by Zero
divide_by_zero = 7 / 0
Output:
ZeroDivisionError: division by zero
Here, the statement is
syntactically correct, but it causes an exception because a number cannot be
divided by zero.
Handling an Exception Example:
try:
divide_by_zero = 7 / 0
except ZeroDivisionError:
print("Cannot divide a number by zero")
Output:
Cannot divide a number by zero
In this example, Python catches the
exception and prevents the program from terminating suddenly.
Difference Between Errors and
Exceptions
|
Errors |
Exceptions |
|
Errors are problems that occur
due to mistakes in the program that prevent successful execution. |
Exceptions are runtime events
that occur while executing a program and interrupt the normal flow. |
|
Errors are generally more serious
and may not be recoverable. |
Exceptions can often be handled
and recovered using exception-handling mechanisms. |
|
Errors are usually caused by
incorrect code, syntax mistakes, or system problems. |
Exceptions are usually caused by
invalid operations or unexpected situations during execution. |
|
Errors may stop the program
before execution begins. |
Exceptions occur after the
program starts running. |
|
Errors are not usually handled by
the programmer. |
Exceptions can be handled using
try, except, finally, and raise statements. |
|
Example: Syntax error,
indentation error, memory error. |
Example: Division by zero, file
not found, invalid input. |
Examples
Error Example (Syntax Error):
print("Hello"
Output:
SyntaxError: unexpected EOF while
parsing
Exception Example (Runtime Error):
x = 10 / 0
Output:
ZeroDivisionError: division by zero
Summary
- Error
→ A serious
problem that prevents the program from working properly.
- Exception
→ A runtime
problem that can be detected and handled by the program. ✅
2. Exception Handling
Exception handling is a mechanism in programming that
allows a program to detect, handle, and respond to runtime errors
(exceptions) without stopping suddenly.
In Python, exception handling helps
prevent program termination by providing alternative actions when an error
occurs.
Need for Exception Handling
- Prevents
the program from crashing unexpectedly.
- Allows
the program to continue execution after handling an error.
- Provides
meaningful error messages to users.
- Helps
programmers identify and fix runtime problems.
- Improves
the reliability and user-friendliness of programs.
Python Exception Handling Keywords
- try
- Contains
the code that may generate an exception.
- except
- Handles
the exception when it occurs.
- else
- Executes
when no exception occurs.
- finally
- Executes
whether an exception occurs or not.
- raise
- Used
to manually generate an exception.
Syntax:
try:
# code that may cause an exception
except ExceptionType:
# code to handle the exception
finally:
# code that always executes
Example:
try:
a = 10
b = 0
result = a / b
print(result)
except ZeroDivisionError:
print("Division by zero is not possible")
finally:
print("Program execution completed")
Output:
Division by zero is not possible
Program execution completed
Conclusion
Exception handling allows Python
programs to manage runtime errors effectively and continue execution safely
instead of stopping abruptly. It makes programs more robust and reliable. ✅
try Block
A try block is a block of
code in Python that contains statements that may cause an exception (runtime
error) during program execution.
Python executes the code inside the
try block. If an exception occurs, the program immediately transfers control to
the corresponding except block to handle the error.
Syntax:
try:
# code that may cause an exception
Example:
try:
num = int(input("Enter a number: "))
result = 10 / num
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
Explanation:
- The
statements inside the try block are executed normally.
- If
the user enters 0, the statement 10 / num causes a
ZeroDivisionError.
- Python
stops executing the try block and moves to the except block.
Important Points:
- A
try block must be followed by at least one except or finally block.
- It
is used to test code that may produce an exception.
- It
prevents the program from terminating suddenly due to runtime errors.
- Only
the code inside the try block is monitored for exceptions.
Example of a successful execution:
Enter a number: 2
5.0
Example when an exception occurs:
Enter a number: 0
Cannot divide by zero
In short, the try block contains
risky code, and it allows Python to detect possible exceptions. ✅
except Block
An except block is a block
of code in Python that is used to handle exceptions raised inside the
try block. It contains instructions that execute when a specific error occurs,
preventing the program from stopping unexpectedly.
Syntax:
try:
# code that may cause an exception
except ExceptionType:
# code to handle the exception
Example:
try:
num = 10 / 0
print(num)
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Explanation:
- The
statement 10 / 0 inside the try block causes a ZeroDivisionError.
- Python
detects the exception and transfers control to the except block.
- The
except block executes the error-handling statement.
Types of except Block:
1. Specific Exception Handling
try:
x = int("abc")
except ValueError:
print("Invalid conversion")
2. Multiple Exception Handling
try:
a = 10 / 0
except (ZeroDivisionError,
ValueError):
print("An error occurred")
3. General Exception Handling
try:
x = 10 / 0
except Exception:
print("Something went wrong")
Important Points:
- An
except block must be associated with a try block.
- It
executes only when an exception occurs.
- It
allows the programmer to handle errors gracefully.
- Multiple
except blocks can be used to handle different types of exceptions.
In short:
The try block contains code that may cause an error, while the except block
contains code that handles that error. ✅
else Block
The else block in Python
exception handling is an optional block that is executed only when no
exception occurs inside the try block.
It is used to define the code that
should run when the try block completes successfully.
Syntax:
try:
# code that may cause an exception
except ExceptionType:
# code to handle exception
else:
# code that executes if no exception occurs
Example:
try:
num1 = 10
num2 = 2
result = num1 / num2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result is:", result)
Output:
Result is: 5.0
Explanation:
- The
code inside the try block executes first.
- Since
no exception occurs (10 / 2 is valid), Python skips the except block.
- The
else block is executed and displays the result.
Example When Exception Occurs:
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
else:
print("Result is:", result)
Output:
Division by zero is not allowed
Here, the else block does not
execute because an exception occurred.
Important Points:
- The
else block is optional.
- It
executes only if the try block runs successfully.
- It
must come after all except blocks.
- It
is useful for separating normal execution code from error-handling code.
In short:
try → Tests risky code
except → Handles errors
else → Runs when no error occurs ✅
finally Block
The finally block in Python
exception handling is an optional block that is always executed, whether
an exception occurs or not.
It is mainly used for cleanup
activities, such as closing files, releasing resources, or performing final
tasks.
Syntax:
try:
# code that may cause an exception
except ExceptionType:
# code to handle exception
finally:
# code that always executes
Example 1: Exception Occurs
try:
num = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Program execution completed")
Output:
Cannot divide by zero
Program execution completed
Example 2: No Exception Occurs
try:
num = 10 / 2
print(num)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("This block always executes")
Output:
5.0
This block always executes
Uses of finally Block:
- Closing
files after reading or writing.
- Releasing
memory or system resources.
- Disconnecting
from databases.
- Executing
important statements that must run regardless of errors.
Important Points:
- The
finally block always executes after try and except.
- It
executes whether an exception occurs or not.
- It
is optional but useful for resource management.
- It
helps ensure that cleanup operations are completed.
In short:
try → Contains risky code
except → Handles exceptions
else → Executes when no exception occurs
finally → Always executes ✅
Complete Example of Exception
Handling
try:
a = int(input("Enter numerator: "))
b = int(input("Enter denominator: "))
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Result =", result)
finally:
print("Program completed")
Advantages of Exception Handling ⭐
- Prevents
sudden termination of programs.
- Makes
programs more reliable.
- Helps
identify and manage errors.
- Improves
program readability and maintenance.
- Provides
user-friendly error messages.
Summary Table
|
Term |
Meaning |
|
Error |
Problem that prevents program
execution |
|
Syntax Error |
Error caused by incorrect Python
syntax |
|
Runtime Error |
Error occurring during program
execution |
|
Logical Error |
Program runs but gives incorrect
output |
|
Exception |
Runtime error that can be handled |
|
try |
Tests code for errors |
|
except |
Handles errors |
|
else |
Runs when no error occurs |
|
finally |
Always executes |
Key Point ⭐
Exception handling allows Python
programs to detect and manage errors using try, except, else, and finally
blocks, making programs stable and reliable.
1. Choose the Correct Answer (MCQ)
i. A collection of modules that
together supply to specific needs or applications is called a:
a) Module b) Package c) Library d) Function
✅ Answer:
b) Package
ii. Which of the following is a
popular Python library used for data manipulation and analysis?
a) Math b) Random c) Pandas d) Turtle
✅ Answer:
c) Pandas
iii. What is a container that
contains various functions to perform specific tasks in Python?
a) Module b) Library c) Package d) Function
✅ Answer:
a) Module
iv. Which statement is used to
access modules or files from a Python package?
a) Include b) Use c) Import d) Access
✅ Answer:
c) Import
v. Which of the following is NOT a
standard way to import a module in Python?
a) import module_name b) from module_name get function_name c) import
module_name as alias d) get function_name from module_name
✅ Answer:
b) from module_name get function_name
vi. Which Python library provides
functions for generating random numbers?
a) Math b) Random c) Pandas d) Matplotlib
✅ Answer:
b) Random
vii. What type of error occurs when
the code violates the rules of the programming language’s syntax?
a) Runtime Error b) Logical Error c) Syntax Error d) Exception
✅ Answer:
c) Syntax Error
viii. Errors detected during
program execution are called:
a) Syntax Errors b) Logical Errors c) Exceptions d) Warnings
✅ Answer:
c) Exceptions
ix. Which block is used to test a
block of code for potential errors in Python?
a) Catch b) Handle c) Try d) Error
✅ Answer:
c) Try
x. Which block in error handling
always executes, regardless of whether an exception occurred or not?
a) Else b) Finally c) Except d) Try
✅ Answer:
b) Finally
2. Short Answer Questions
a) Define the term “module” in the
context of Python programming.
A module is a Python file
containing functions, variables, and classes that can be imported and reused in
other Python programs.
b) What is the relationship between
modules and libraries in Python?
A library is a collection of
multiple modules that provide related functions and features for solving
specific problems.
Example: The Python Math library contains
mathematical modules and functions.
c) Give an example of a built-in
Python library and its purpose.
Math library is a built-in Python library used
for performing mathematical operations such as square root, trigonometric
functions, and logarithms.
Example:
import math
print(math.sqrt(25))
d) Explain why packages are useful
for code organization and reusability.
Packages organize related modules
into a structured folder. They make programs easier to manage, maintain, and
reuse.
e) What is the purpose of using an
alias when importing a module? Provide an example.
An alias gives a shorter name to a
module, making it easier to use.
Example:
import pandas as pd
Here, pd is an alias for the Pandas
library.
f) Name two functions provided by
the Python math library.
Two functions are:
- math.sqrt()
– finds square root
- math.factorial()
– calculates factorial of a number
g) What is a runtime error? Give an
example.
A runtime error occurs while
a program is running due to an unexpected problem.
Example:
10 / 0
This causes a ZeroDivisionError.
h) Explain the difference between
an error and an exception in Python.
- Error: A problem that prevents a
program from working correctly, such as syntax errors.
- Exception: A runtime problem that can be
detected and handled by the program.
i) What is the role of the except
block in a try-except statement?
The except block handles
exceptions raised inside the try block and prevents the program from stopping
suddenly.
j) When is the else block in a
try-except-else statement executed?
The else block executes only
when the try block completes successfully without any exception.
3. Long Answer Questions
a) Explain the concepts of Python
libraries and packages, highlighting their importance in software development.
Python Libraries
A Python library is a
collection of pre-written modules and functions that help programmers perform
different tasks without writing code from scratch.
Examples:
- Math – mathematical calculations
- Pandas – data analysis
- Matplotlib – data visualization
Python Packages
A package is a collection of
related modules stored together in a directory. Packages help organize large
programs into smaller, manageable parts.
Importance of Libraries and
Packages
- Reduce
programming effort by providing ready-made functions.
- Improve
code reusability.
- Make
programs easier to organize and maintain.
- Increase
development speed.
- Provide
tested and reliable solutions.
b) Introduce three popular Python
libraries: Pandas, Turtle, and Matplotlib.
1. Pandas
Purpose:
Pandas is used for data manipulation, analysis, and handling large datasets.
Example:
import pandas as pd
data = pd.Series([10, 20, 30])
print(data)
2. Turtle
Purpose:
Turtle is a graphics library used for drawing shapes and learning programming
concepts.
Example:
import turtle
turtle.forward(100)
turtle.done()
3. Matplotlib
Purpose:
Matplotlib is used for creating graphs and data visualizations.
Example:
import matplotlib.pyplot as plt
plt.plot([1,2,3],[4,5,6])
plt.show()
c) Discuss different types of
errors in Python programs.
1. Syntax Error
A syntax error occurs when the
rules of Python language are violated.
Example:
print("Hello"
Impact:
The program cannot run until the error is corrected.
2. Runtime Error
A runtime error occurs during
program execution.
Example:
x = 10 / 0
Impact:
The program stops unexpectedly unless the error is handled.
3. Logical Error
A logical error occurs when the
program runs successfully but produces incorrect results.
Example:
length = 5
breadth = 10
area = length + breadth
(Correct formula should be length ×
breadth.)
Impact:
The output is wrong even though the program executes.
d) Explain the importance of error
handling in Python.
Error handling is a process of managing runtime
errors and exceptions to prevent programs from crashing.
Importance of Error Handling:
- Prevents
sudden program termination.
- Improves
program reliability.
- Provides
meaningful error messages.
- Allows
programs to continue execution after handling errors.
- Helps
manage unexpected situations.
Python uses:
- try → Contains risky code
- except → Handles errors
- else → Executes when no error
occurs
- finally → Always executes
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
Thus, error handling makes Python
programs safer, stable, and user-friendly. ✅
Sample Python Programs
1. Program to 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)
Output Example:
Enter first number: 5
Enter second number: 10
Sum of 5 and 10 is 15
Explanation:
This program takes two numbers from the user and calculates their sum using the
+ operator.
2. Program to Check Whether 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.")
Explanation:
The if-elif-else statement checks different conditions and displays the type of
number.
3. Program to Check Whether a
Person is 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.")
Explanation:
If the age is 18 or above, the person is considered an adult.
4. Program to Create a File and
Write a Message
file =
open("message.txt", "w")
file.write("Hello, welcome to
file handling in Python!")
file.close()
print("File created and
message written successfully.")
Explanation:
This program creates a file named message.txt, writes a message, and closes the
file.
5. Function to Calculate Area of
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))
Formula:
6. Function to Check Even or Odd
Number
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))
Explanation:
A number is even if it is completely divisible by 2.
7. Function to Return 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)
print("Cube:", cb)
Explanation:
- n
** 2 calculates square.
- n
** 3 calculates cube.
8. Program Using for Loop to Print
Numbers 1 to 10
for i in range(1, 11):
print(i)
Output:
1
2
3
4
5
6
7
8
9
10
9. Program Using while Loop to Find
Sum of First 10 Natural Numbers
sum = 0
i = 1
while i <= 10:
sum += i
i += 1
print("Sum of first 10 natural
numbers:", sum)
Output:
Sum of first 10 natural numbers: 55
10. Program to Print Even Numbers
from 1 to 20
for i in range(2, 21, 2):
print(i)
Output:
2
4
6
8
10
12
14
16
18
20
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))
Formula:
Explanation:
- P =
Principal amount
- T =
Time period
- R =
Rate of interest (default value = 10%)
✅ These programs cover important
Class 10 Python topics:
1. Handle Division by Zero Error
(ZeroDivisionError)
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
result = a / b
print("Result =", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero")
print("Program executed
successfully")
Output:
Enter first number: 10
Enter second number: 0
Error: Cannot divide by zero
Program executed successfully
2. Handle Invalid Input
(ValueError)
try:
age = int(input("Enter your age: "))
print("Your age is", age)
except ValueError:
print("Error: Please enter only numbers")
Example:
Enter your age: abc
Error: Please enter only numbers
3. Multiple Exception Handling
try:
x = int(input("Enter a number: "))
y = int(input("Enter another number: "))
print("Division =", x/y)
except ValueError:
print("Invalid input")
except ZeroDivisionError:
print("Cannot divide by zero")
4. Using else with Exception
Handling
try:
num = int(input("Enter a number: "))
except ValueError:
print("Invalid number")
else:
print("You entered:", num)
Concept:
- try
→ risky code
- except
→ handles error
- else
→ runs when no error occurs
5. Using finally Block
try:
file = open("data.txt", "r")
print(file.read())
except FileNotFoundError:
print("File does not exist")
finally:
print("File operation completed")
Concept:
finally always executes whether error occurs or not.
6. File Handling Error Program
try:
f = open("student.txt", "r")
data = f.read()
print(data)
except FileNotFoundError:
print("Error: File not found")
finally:
print("Closing program")
7. Handling List Index Error
try:
numbers = [10, 20, 30]
index = int(input("Enter index: "))
print(numbers[index])
except IndexError:
print("Error: Index out of range")
except ValueError:
print("Enter a valid integer")
8. Custom Exception Using raise
try:
marks = int(input("Enter marks: "))
if marks < 0 or marks > 100:
raise Exception("Marks must be
between 0 and 100")
print("Marks =", marks)
except Exception as e:
print("Error:", e)
9. Password Validation Using
Exception
try:
password = input("Enter password: ")
if len(password) < 8:
raise ValueError("Password must
contain minimum 8 characters")
print("Password accepted")
except ValueError as e:
print(e)
10. ATM Withdrawal Example
try:
balance = 5000
withdraw = int(input("Enter withdrawal amount: "))
if withdraw > balance:
raise Exception("Insufficient
balance")
print("Remaining balance:", balance - withdraw)
except Exception as e:
print("Transaction failed:", e)
Important Python Error Types for
Exam:
|
Exception |
Meaning |
|
ZeroDivisionError |
Division by zero |
|
ValueError |
Wrong value entered |
|
TypeError |
Wrong data type |
|
IndexError |
Invalid list index |
|
KeyError |
Dictionary key not found |
|
FileNotFoundError |
File does not exist |
|
NameError |
Variable not defined |
|
Exception |
General exception |
These programs cover the main Python
Error Handling concepts: try, except, else, finally, and raise.
⭐ Most Important (High Probability)
1. Division by Zero Handling
(ZeroDivisionError) ⭐⭐⭐⭐⭐
Why important: Basic example of try-except.
try:
a = int(input("Enter a: "))
b = int(input("Enter b: "))
print(a/b)
except ZeroDivisionError:
print("Cannot divide by zero")
2. Invalid Input Handling
(ValueError) ⭐⭐⭐⭐⭐
try:
num = int(input("Enter number: "))
print(num)
except ValueError:
print("Invalid input")
3. Multiple Exception Handling ⭐⭐⭐⭐⭐
Question often asked:
"Write a program to handle multiple exceptions."
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print(a/b)
except ValueError:
print("Enter valid numbers")
except ZeroDivisionError:
print("Division by zero is not possible")
4. File Handling Exception
(FileNotFoundError) ⭐⭐⭐⭐
Common theory + practical question
try:
file = open("example.txt", "r")
print(file.read())
except FileNotFoundError:
print("File not found")
5. finally Block Program ⭐⭐⭐⭐
Question: "Explain finally block with
example."
try:
x = 10/2
print(x)
except:
print("Error occurred")
finally:
print("Execution completed")
6. Custom Exception Using raise ⭐⭐⭐⭐
Important for understanding
user-defined errors.
try:
age = int(input("Enter age: "))
if age < 18:
raise Exception("Not
eligible")
print("Eligible")
except Exception as e:
print(e)
4.6 File Handling using Panda
Library
A file is a collection of
data stored permanently on a storage device (such as a hard disk) and
identified by a unique filename. Files are used to store data
temporarily or permanently.
Python provides several built-in
functions and methods for:
- Creating
files
- Opening
files
- Reading
data from files
- Writing
data into files
- Closing
files
For data analysis, Python provides
the Pandas library, which makes importing, processing, analyzing, and
manipulating data easier.
Pandas Library
Pandas is an open-source Python library
used for data analysis and data handling.
It provides powerful data
structures:
- Series → One-dimensional labeled
data
- DataFrame → Two-dimensional table-like
data (rows and columns)
Pandas is built on important
libraries such as:
- NumPy → Numerical computations
- Matplotlib → Data visualization
4.6.1 Concept of File Handling in
Python
File handling in Python refers to
the process of performing operations on files stored in a computer system. It
allows a program to create, open, read, write, append, and close files.
Files are used to store data permanently so that the data can be accessed
whenever required.
Python provides built-in functions
and methods for handling files. The Pandas library is also used for
efficient file handling, especially for data analysis. It provides simple
functions to read and write different file formats such as CSV, Excel, and
JSON (JavaScript Object Notation).
Benefits of File Handling in Python
File handling in Python provides
several advantages for storing, accessing, and managing data efficiently. The
major benefits are:
1. Versatility
File handling in Python allows
users to perform a wide range of operations on files, such as:
- Creating
files
- Reading
data from files
- Writing
data into files
- Appending
new data
- Renaming
files
- Deleting
files
2. Flexibility
Python file handling is highly
flexible because it supports different types of files, such as:
- Text
files
- Binary
files
- CSV
files
- Excel
files
It also allows various operations
like reading, writing, and updating file contents according to requirements.
3. User Friendly
Python provides simple and
easy-to-use functions and methods for file handling. It allows programmers to
create, access, and manipulate files with fewer lines of code, making file
operations easier to understand.
4. Cross-platform Compatibility
Python file handling functions work
on different operating systems such as Windows, Mac OS, and Linux. This
allows Python programs to run smoothly across multiple platforms without major
changes.
Conclusion
File handling in Python helps in
efficient data storage and management. Its versatility, flexibility,
user-friendly features, and cross-platform support make it an important part of
Python programming.
Difficulties of File Handling in
Python
Although file handling in Python
provides many advantages, it also has some difficulties and challenges. The
major difficulties are:
1. Error-Prone
File handling operations can
generate errors if the code is not written properly or if there are problems
with the file system. Common errors include:
- File
not found
- Incorrect
file path
- Permission
issues
- File
access conflicts
2. Security Risks
File handling may create security
risks, especially when programs accept input from users. Improper handling of
files may allow unauthorized access, modification, or deletion of sensitive
data.
3. Complexity
File handling can become complex
when working with advanced file formats or performing complicated operations.
Programmers need to carefully manage files to avoid data loss and ensure proper
security.
4. Performance Issues
File handling operations may be
slower when dealing with:
- Very
large files
- Complex
file processing tasks
- Large
amounts of data
This can affect the overall
performance of a program.
Conclusion
Despite these difficulties, Python
provides simple and powerful file handling features. Proper error handling,
security measures, and efficient programming practices can help overcome these
challenges.
4.6.2 Concept of Mode of File
Handling (Read, Write, and Append a File)
File handling modes define how a
file is accessed and what operations can be performed on that file. In Python,
before performing any file operation, a file must be opened using the built-in open()
function.
The open() function allows a
programmer to open a file in different modes such as read, write, and append.
Syntax:
file = open("filename",
"mode")
or
with open("filename",
"mode") as file:
The with statement automatically
closes the file after completing the operation.
Different File Access Modes in
Python
|
Mode |
Name |
Description |
|
r |
Read mode |
Opens a file for reading only. It
gives an error if the file does not exist. |
|
w |
Write mode |
Opens a file for writing. It
creates a new file if it does not exist and overwrites existing content. |
|
a |
Append mode |
Opens a file for adding new data
at the end. It creates a file if it does not exist. |
|
x |
Create mode |
Creates a new file. It gives an
error if the file already exists. |
|
t |
Text mode |
Opens a file in text format
(default mode). |
|
b |
Binary mode |
Opens a file in binary format. |
1. Reading a File in Python
(Complete Exam Answer)
Introduction
Reading a file means accessing and
retrieving the data stored inside an existing file. In Python, before reading
any file, the file must first be opened in read mode (r).
Python provides different methods
to read data from a file. After completing the reading operation, the file
should be closed using the close() method to release system resources.
Opening a File in Read Mode
Syntax:
file = open("filename",
"r")
Where:
- filename = name of the file to be
opened
- r = read mode
Example: Reading a File
file = open("Test.txt",
"r")
content = file.read()
print(content)
file.close()
Explanation:
- open()
opens the file in read mode.
- read()
reads the content of the file.
- print()
displays the content.
- close()
closes the file.
Methods of Reading a File in Python
Python provides several methods for
reading file contents:
1. read() Method
The read() method is used to
read the entire content of a file at once.
Syntax:
file.read()
Example:
file = open("Test.txt",
"r")
data = file.read()
print(data)
file.close()
Output:
Hello Python Programming
2. read(size) Method
The read(size) method is
used to read a specific number of characters from a file.
The value given inside the
parentheses specifies the number of characters to be read.
Syntax:
file.read(size)
Where:
- size = number of characters to
read
Example:
file = open("Test.txt",
"r")
data = file.read(10)
print(data)
file.close()
If the file contains:
Hello Python Programming
Output:
Hello Pyth
Explanation:
Only the first 10 characters are read from the file.
3. readline() Method
The readline() method is
used to read only the first line of a file.
Syntax:
file.readline()
Example:
file = open("Test.txt",
"r")
line = file.readline()
print(line)
file.close()
Explanation:
- It
reads one line at a time.
- It
is useful when working with large files.
4. readlines() Method
The readlines() method is
used to read all lines from a file and returns them as a list.
Syntax:
file.readlines()
Example:
file = open("Test.txt",
"r")
lines = file.readlines()
print(lines)
file.close()
Output:
['First line\n', 'Second line\n',
'Third line']
Summary of Reading Methods
|
Method |
Description |
|
read() |
Reads the complete content of a
file |
|
read(size) |
Reads a specified number of
characters from a file |
|
readline() |
Reads only one line from a file |
|
readlines() |
Reads all lines of a file and
returns them as a list |
Example Showing All Reading Methods
file = open("Test.txt",
"r")
print(file.read(5))
file.seek(0)
print(file.readline())
file.seek(0)
print(file.readlines())
file.close()
Closing a File
After completing file operations,
the file should be closed using the close() method.
Syntax:
file.close()
Importance of Closing a File:
- Releases
system resources.
- Prevents
unnecessary memory usage.
- Ensures
proper file management.
- Prevents
data corruption.
Conclusion
Reading a file is an important
operation in Python file handling. Python provides different reading methods
such as read(), read(size), readline(), and readlines() to access file
data according to requirements. Proper opening and closing of files ensures
efficient and safe file handling.
2. Creating a New File in Python
(Complete Exam Answer)
Introduction
Creating a new file is an important
operation in file handling. In Python, a new file can be created by using the
built-in open() function with specific file access modes.
Python provides two main modes for
creating a new file:
- x
mode (Create mode)
- w
mode (Write mode)
1. Creating a File using x Mode
The x mode is used to create
a new empty file.
Features of x mode:
- Creates
a new file if the file does not exist.
- Generates
an error if a file with the same name already exists.
- It
is used only for creating new files.
Syntax:
file = open("filename",
"x")
Example:
file =
open("student.txt", "x")
file.close()
Explanation:
- A
new empty file named student.txt is created.
- If
student.txt already exists, Python generates a FileExistsError.
2. Creating a File using w Mode
The w mode is also used to
create a file.
Features of w mode:
- Creates
a new file if it does not exist.
- If
the file already exists, it overwrites the existing content.
- It
allows writing data into the file.
Syntax:
file = open("filename",
"w")
Example:
file =
open("student.txt", "w")
file.write("Python File
Handling")
file.close()
Explanation:
- If
student.txt does not exist, a new file is created.
- If
the file exists, the previous content is removed and new content is
written.
Difference Between x and w Mode
|
Feature |
x Mode |
w Mode |
|
Purpose |
Creates a new file |
Creates and writes to a file |
|
Existing file |
Gives an error |
Overwrites existing file |
|
Writing data |
Not mainly used for writing |
Used for writing data |
|
If file does not exist |
Creates file |
Creates file |
Example Program: Creating a New
File
# Creating a new file
file = open("data.txt",
"x")
print("File created
successfully")
file.close()
Output:
File created successfully
Important Points
- The
open() function is used to create files in Python.
- x
mode is safer because it prevents accidental overwriting.
- w
mode can overwrite existing data.
- Always
close the file after completing operations using close().
Conclusion
Python provides simple methods to
create new files using x and w modes. The x mode is used for creating a new
file only, while the w mode creates a file and allows writing data. Proper use
of these modes helps in effective file management.
3. Writing to a File in Python
(Complete Exam Answer)
Introduction
Writing to a file means storing or
adding data into a file. In Python, writing operations are performed using the write()
method. A file must be opened in write mode (w) before writing data into
it.
If the file already exists, the write
mode (w) removes the existing content and adds new content. If the file
does not exist, Python creates a new file automatically.
Opening a File in Write Mode
Syntax:
file = open("filename",
"w")
Where:
- filename = name of the file
- w = write mode
Example: Writing Data into a File
file = open("Test.txt",
"w")
file.write("Hello,
World!")
file.close()
Explanation:
- open()
opens the file in write mode.
- write()
writes the specified string into the file.
- close()
closes the file after completing the operation.
Output in File (Test.txt):
Hello, World!
Methods of Writing Data into a File
Python provides two main methods
for writing data:
1. write() Method
The write() method is used
to write a single string into a file.
Syntax:
file.write(string)
Example:
with open("file.txt",
"w") as file:
file.write("This is the first line\n")
file.write("This is the second line\n")
file.write("This is the third line")
Output:
This is the first line
This is the second line
This is the third line
2. writelines() Method
The writelines() method is
used to write multiple strings into a file at once.
Syntax:
file.writelines(list)
Example:
file = open("file.txt",
"w")
file.writelines([
"This is the first line\n",
"This is the second line\n",
"This is the third line"
])
file.close()
Output:
This is the first line
This is the second line
This is the third line
Writing Data using Append Mode (a)
Append mode is used to add new data
at the end of an existing file without deleting previous content.
Syntax:
file = open("filename",
"a")
Example:
file = open("Test.txt",
"a")
file.write("\nPython
programming is fun")
file.close()
Output in File:
Hello, World!
Python programming is fun
Difference Between write() and
writelines()
|
write() |
writelines() |
|
Writes a single string at a time |
Writes multiple strings at once |
|
Takes a string as input |
Takes a list of strings as input |
|
Used for small amounts of data |
Used for multiple lines of data |
Important Points
- Writing
requires opening a file in w or a mode.
- w
mode overwrites existing data.
- a
mode adds data at the end of the file.
- write()
and writelines() are used to insert data.
- The
file should be closed after writing.
Conclusion
Writing to a file is an important
file handling operation in Python. The write() method is used to store single
strings, while the writelines() method is used to store multiple lines. Proper
use of write and append modes helps in efficient data storage and management.
4. Append Mode
4. Append Mode in Python
(Complete Exam Answer)
Introduction
Append mode is a file handling mode
in Python that is used to add new data to an existing file without removing
the previous content. In Python, append mode is represented by 'a'.
When a file is opened in append
mode:
- New
data is added at the end of the file.
- Existing
data remains unchanged.
- If
the file does not exist, Python creates a new file automatically.
Opening a File in Append Mode
Syntax:
file = open("filename",
"a")
Where:
- filename = name of the file
- a = append mode
Example: Writing Data using Append
Mode
file = open("Test.txt",
"a")
file.write("\nPython
programming is fun")
file.close()
Before Append Operation (Test.txt):
Hello World!
After Append Operation:
Hello World!
Python programming is fun
Explanation:
- The
file is opened using append mode (a).
- New
text is added after the existing content.
- The
previous data is not deleted.
- The
file is closed using close().
Features of Append Mode
- Adds
data at the end
- New
information is always written after existing data.
- Preserves
existing data
- Old
content remains safe and unchanged.
- Creates
a new file if it does not exist
- Python
automatically creates the file.
- Cannot
read data
- Append
mode is mainly used for writing additional information.
Example Program: Append Data into a
File
# Opening file in append mode
file =
open("student.txt", "a")
file.write("\nName: Ram")
file.write("\nAge: 20")
file.close()
print("Data added
successfully")
Output:
Data added successfully
Difference Between Write Mode (w)
and Append Mode (a)
|
Write Mode (w) |
Append Mode (a) |
|
Deletes existing content |
Keeps existing content |
|
Writes new data from the
beginning |
Adds data at the end |
|
Used for replacing file content |
Used for adding new information |
|
Creates a file if it does not
exist |
Creates a file if it does not
exist |
Conclusion
Append mode (a) is used in Python
to add new data to an existing file without losing previous information. It is
commonly used for maintaining records, logs, and updating files where old data
must be preserved.
5. Closing a File
5. Closing a File in Python
(Complete Exam Answer)
Introduction
Closing a file is an important step
in file handling after completing all file operations such as reading, writing,
or appending data. In Python, the close() method is used to close an
opened file.
When a file is closed, all
resources used by the file are released, and the file becomes unavailable for
further operations until it is opened again.
Syntax:
file.close()
Where:
- file = file object created while
opening the file.
- close() = method used to close the
file.
Example: Closing a File
file = open("Test.txt",
"r")
content = file.read()
print(content)
file.close()
Explanation:
- The
file is opened in read mode using open().
- The
read() method reads the content of the file.
- The
close() method closes the file after completing the operation.
Importance of Closing a File
1. Releases System Resources
- Closing
a file frees memory and other system resources used by the file.
2. Prevents Data Loss
- It
ensures that all written data is properly saved to the file.
3. Improves File Security
- A
closed file cannot be accessed or modified accidentally by other
operations.
4. Good Programming Practice
- It
is recommended to close files after completing file operations to maintain
proper file management.
Closing a File Using with Statement
Python also provides the with
statement to automatically close files after completing the operation.
Example:
with open("Test.txt",
"r") as file:
data = file.read()
print(data)
Explanation:
- The
with statement automatically closes the file.
- It
reduces the chance of forgetting to close a file.
Conclusion
The close() method is used to
terminate file operations and release system resources. Closing a file after
use is an essential practice in Python file handling because it prevents data
loss and ensures efficient resource management.
File handling modes in Python allow
programmers to perform different operations such as reading, writing, and
appending data. The main file modes (r, w, and a) help in efficient data
storage and management. Proper opening and closing of files ensures safe and
effective file processing.
4.6.3 Read and Write CSV File Using
Standard Library (e.g., Pandas)
(Complete Exam Answer)
Introduction
CSV (Comma Separated Values) is one of the most common file
formats used for importing and exporting data between spreadsheets and
databases. A CSV file stores data in a tabular form where each value is
separated by a comma (,).
CSV files are generally used by
applications that handle large amounts of data. Python provides different
methods to read and write CSV files using the built-in csv module and
the Pandas library.
Structure of a CSV File
A CSV file contains rows and
columns. Each data value is separated by a comma.
Example:
Name,Age,Address
Ram,20,Kathmandu
Hari,21,Butwal
Here:
- First
row represents column names (headers).
- Other
rows represent data records.
Reasons Why CSV Files Are Favoured
(Exam Answer)
CSV (Comma Separated Values) files
are widely used for storing and exchanging data because of their simplicity,
compatibility, and ease of use. The main reasons why CSV files are favoured
are:
1. Portability
CSV files are plain text files,
which makes them easy to open, edit, and transfer across different applications
and platforms. They can be accessed using spreadsheet programs such as Microsoft
Excel, Google Sheets, and text editors.
2. Simplicity
The structure of CSV files is
straightforward. Data is stored in rows and columns, with values separated by
commas. This simple format makes CSV files easy to create, read, and process
using programming languages.
3. Wide Support
Almost every programming language,
database system, and spreadsheet application supports CSV files. Python also
provides built-in support for reading and writing CSV data.
Conclusion
CSV files are preferred because
they are portable, simple, and widely supported. These features make them
suitable for storing, sharing, and processing large amounts of structured data.
Benefits of the CSV Module in
Python
(Exam Answer)
The CSV module is a built-in
Python module used for working with CSV (Comma Separated Values) files. It
provides functions for reading and writing data in CSV format. The major
benefits of the CSV module are:
1. Built-in and Easy to Use
The CSV module is already available
in Python, so no additional installation is required. It provides simple
functions that make reading and writing CSV files easy.
Example:
import csv
2. Flexible and Adaptable
The CSV module can handle different
types of CSV formats. It supports various:
- Delimiters
- Quoting
styles
- Escape
characters
This makes it suitable for working
with CSV files from different sources.
3. Memory Efficient
The CSV module reads and writes
data row by row instead of loading the entire file into memory at once.
Therefore, it can efficiently handle large CSV files with less memory usage.
Conclusion
The CSV module provides a simple,
flexible, and efficient way to process CSV files in Python. Its built-in
features and memory efficiency make it useful for handling structured data.
Reading CSV File in Python
(Complete Exam Answer)
Introduction
Reading a CSV file means accessing
and retrieving data stored in a CSV (Comma Separated Values) file. Python
provides different methods to read CSV files. A CSV file can be read using the built-in
csv module or the Pandas library.
Methods of Reading CSV Files in
Python
There are two main ways to read CSV
files:
- Using
the CSV module
- Using
the Pandas library
a) Using the CSV Module
(Exam Answer)
Python provides a built-in csv
module for working with CSV (Comma Separated Values) files. It provides
basic functionality for reading and writing CSV data.
To read a CSV file using the CSV
module, the file is first opened using Python’s built-in open() function
in read mode. The file object returned by open() is then passed to the csv.reader()
function, which reads the data from the CSV file.
Steps to Read a CSV File Using CSV
Module
Step 1: Import CSV Module
import csv
Step 2: Open the CSV File
The file is opened in read mode
('r').
with open('data.csv', 'r') as
csvfile:
Step 3: Create a Reader Object
The csv.reader() function is used
to create a reader object.
csv_reader = csv.reader(csvfile)
Step 4: Read Rows from CSV File
A loop is used to access each row
of the CSV file.
for row in csv_reader:
print(row)
Complete Example Program
import csv
# Open CSV file in read mode
with open('data.csv', 'r') as
csvfile:
# Create reader object
csv_reader = csv.reader(csvfile)
# Read each row from CSV file
for row in csv_reader:
print(row)
Explanation
- import
csv loads the CSV module.
- open()
opens the CSV file.
- csv.reader()
converts the file object into a CSV reader object.
- The
for loop reads and displays each row from the file.
Advantages of Using CSV Module
- It
is a built-in Python module, so no extra installation is required.
- It
is simple and easy to implement.
- It
supports different CSV formats.
- It
reads and writes data efficiently.
Conclusion
The CSV module provides a simple
way to read and process CSV files in Python. It is suitable for basic CSV
operations and can efficiently handle structured data.
b) Using the Pandas Library
(Exam Answer)
Pandas is a powerful Python library used
for data manipulation, analysis, and processing. It provides an easy and
efficient way to read and write CSV files. Pandas uses the DataFrame
data structure to store and manage tabular data.
The read_csv() function of
Pandas is used to read data from a CSV file.
Steps to Read a CSV File Using
Pandas
Step 1: Import Pandas Library
First, the Pandas library is
imported using the following statement:
import pandas as pd
Step 2: Load CSV File Using
read_csv()
The read_csv() function is used to
read the CSV file and store the data in a DataFrame.
Syntax:
pandas.read_csv(filename,
delimiter=',')
Where:
- filename = name of the CSV file
- delimiter=',' = separates values using
commas
Example:
import pandas as pd
data =
pd.read_csv("Salary_Data.csv")
print(data)
Output:
Years Experience Salary
0 1.1 39343
1 1.3 46205
2 1.5 37731
3 2.0 43525
Accessing Column Names
The .columns attribute is
used to display the field names (column names) of the DataFrame.
Example:
data.columns
Output:
Index(['Years Experience',
'Salary'])
Accessing Data Rows/Columns
The data stored in a DataFrame can
be accessed using the field (column) names.
Example:
data.Salary
This displays all values stored in
the Salary column.
Complete Example Program
import pandas as pd
# Reading CSV file
df =
pd.read_csv("Data.csv")
# Displaying CSV data
print(df)
Advantages of Using Pandas for
Reading CSV Files
- Provides
simple and easy-to-use functions.
- Handles
large datasets efficiently.
- Stores
data in a DataFrame structure.
- Allows
easy data filtering and analysis.
- Supports
integration with other data analysis libraries.
Conclusion
Pandas provides a convenient and
powerful method for reading CSV files in Python. The read_csv() function loads
CSV data into a DataFrame, allowing easy data analysis and manipulation.
Writing to a CSV File Using Pandas
(Complete Exam Answer)
Introduction
Writing to a CSV file means storing
data into a CSV (Comma Separated Values) file. In Python, the Pandas library
provides the to_csv() method to write data into a CSV file.
In Pandas, data is first created as
a DataFrame using the pd.DataFrame() method, and then the DataFrame is
written into a CSV file using the to_csv() function.
Steps to Write Data into a CSV File
Using Pandas
Step 1: Import Pandas Library
The Pandas library is imported
using:
import pandas as pd
Step 2: Create a Pandas DataFrame
A DataFrame is created using the pd.DataFrame()
method.
Syntax:
pd.DataFrame(data, columns)
Where:
- data = records or values to be
stored
- columns = column or field names
Example:
header = ['Name', 'M1 Score', 'M2
Score']
data = [
['Sanskar', 62, 80],
['Sambriddhi', 45, 56],
['Aurora', 85, 98]
]
df = pd.DataFrame(data,
columns=header)
Step 3: Write Data into CSV File
The to_csv() method is used
to write the DataFrame into a CSV file.
Syntax:
DataFrame.to_csv(filename, sep=',',
index=False)
Where:
- filename = name of the CSV file
- sep=',' = separator used between
values (comma by default)
- index=False = removes automatic index
numbers
Example:
df.to_csv("Stu_data.csv",
index=False)
Complete Program: Writing Data to
CSV File
import pandas as pd
# Data to be written
data = {
'Product': ['Laptop', 'Smartphone', 'Tablet'],
'Price': [75000, 15000, 20000],
'Quantity': [3, 10, 5]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Writing DataFrame to CSV file
df.to_csv("products.csv",
index=False)
print("Data written to
products.csv successfully.")
Output
Data written to products.csv
successfully.
The created CSV file will contain:
|
Product |
Price |
Quantity |
|
Laptop |
75000 |
3 |
|
Smartphone |
15000 |
10 |
|
Tablet |
20000 |
5 |
Important Points
- pd.DataFrame()
converts data into a tabular format.
- to_csv()
saves the DataFrame as a CSV file.
- index=False
prevents writing row index numbers into the file.
- Pandas
makes CSV writing easier and efficient for large datasets.
Conclusion
Pandas provides a simple and
effective way to write data into CSV files. By creating a DataFrame and using
the to_csv() method, data can be stored and shared easily in CSV format.
1. Choose the Correct Answer
i. Which Python library is
particularly useful for simplifying file handling of structured data like CSV
files?
a) math b) random c) pandas ✅ d) turtle
ii. What is the primary function
used in Pandas to read data from a CSV file?
a) open() b) read_file() c) pd.read_csv() ✅ d) df.read_csv()
iii. When reading a CSV file with
Pandas, which parameter in read_csv() is used to specify the separator between
values?
a) separator b) sep ✅ c) delimiter d) value_sep
iv. What attribute of a Pandas
DataFrame can be used to obtain the header or field names after reading a CSV
file?
a) headers b) columns ✅ c) fields d) names
v. Which Pandas method is used to
write a DataFrame to a CSV file?
a) write_csv() b) to_file() c) df.to_csv() ✅ d) pd.write_csv()
vi. When writing a DataFrame to a
CSV file using to_csv(), what does the parameter index=False do?
a) It includes the index as a column in the CSV b) It removes the header row
from the CSV c) It excludes the index column from the CSV ✅ d) It sorts the data based on the
index
vii. What is the default separator
used by Pandas when reading or writing CSV files?
a) semicolon (;) b) tab (\t) c) comma (,) ✅ d) space ( )
viii. Which mode should be used
with the built-in open() function if you want to read a file?
a) “w” b) “a” c) “r” ✅ d) “x”
ix. Which mode, when used with the
built-in open() function, will overwrite the file if it exists or create a new
file if it doesn’t?
a) “r” b) “a” c) “w” ✅ d) “x”
x. Which Pandas function is used to
create a DataFrame from a dictionary or a list of lists?
a) read_csv() b) to_csv() c) pd.DataFrame() ✅ d) create_df()
2. Short Answer Questions
i. What are the primary advantages
of using the Pandas library for file handling in Python?
Answer:
The main advantages of using Pandas are:
- It
provides simple functions for reading and writing files.
- It
can handle large datasets efficiently.
- It
provides DataFrame structures for easy data manipulation.
- It
supports different file formats like CSV, Excel, and JSON.
- It
makes data analysis easier.
ii. Explain the concept of a CSV
file and why it is a common format for data exchange.
Answer:
CSV (Comma Separated Values) is a file format used to store tabular data in
rows and columns. Each value is separated by a comma.
CSV files are commonly used because
they are:
- Simple
and easy to understand.
- Portable
across different applications.
- Supported
by almost all programming languages and spreadsheet software.
iii. What is the first step you
need to take to use the Pandas library in your Python script for file handling?
Answer:
The first step is to import the Pandas library into the Python program.
Example:
import pandas as pd
iv. Describe the basic syntax for
reading a CSV file into a Pandas DataFrame.
Answer:
The syntax for reading a CSV file
is:
data =
pd.read_csv("filename.csv")
Example:
df =
pd.read_csv("student.csv")
v. How can you access a specific
column of data after reading a CSV file into a Pandas DataFrame?
Answer:
A specific column can be accessed using the column name.
Example:
df.Name
or
df["Name"]
vi. Explain the basic syntax for
writing a Pandas DataFrame to a CSV file.
Answer:
The syntax is:
DataFrame.to_csv("filename.csv",
index=False)
Example:
df.to_csv("student.csv",
index=False)
vii. What happens if you try to
open a non-existent file in read ("r") mode using the built-in open()
function?
Answer:
If a file does not exist and we try to open it in read mode ("r"),
Python generates a FileNotFoundError.
viii. Explain the difference
between write ("w") mode and append ("a") mode.
Answer:
|
Write Mode (w) |
Append Mode (a) |
|
Writes new data into a file. |
Adds new data at the end of an
existing file. |
|
Removes previous content. |
Keeps previous content unchanged. |
|
Creates a file if it does not
exist. |
Creates a file if it does not
exist. |
ix. Why is it important to close a
file after read or write operations?
Answer:
Closing a file is important because:
- It
releases system resources.
- It
prevents data loss.
- It
ensures that data is properly saved.
- It
improves file security.
3. Long Answer Questions
i. Steps to Read Data from a CSV
File Using Pandas
Steps:
Step 1: Import the Pandas library.
import pandas as pd
Step 2: Use the read_csv() function to
load the CSV file.
df =
pd.read_csv("filename.csv")
Step 3: Display or analyze the DataFrame.
print(df)
Program:
import pandas as pd
# Reading CSV file
data =
pd.read_csv("student.csv")
# Displaying data
print(data)
ii. Program Using Pandas for
Student Data Analysis
Problem:
CSV file name: student_data.csv
Columns:
- Name
- Age
- Grade
Program:
import pandas as pd
# a. Read CSV file into DataFrame
df =
pd.read_csv("student_data.csv")
# b. Print first 5 rows
print(df.head())
# c. Calculate average age
average_age =
df["Age"].mean()
print("Average Age:",
average_age)
# d. Create DataFrame containing
only Grade A students
grade_A_students =
df[df["Grade"] == "A"]
print(grade_A_students)
Explanation:
- pd.read_csv()
→ Reads CSV file.
- head()
→ Displays first 5 rows.
- mean()
→ Calculates average value.
- Filtering
condition df["Grade"]=="A" → Selects only students
with Grade A.
✅ These answers are exam-ready
for Class 10 Computer Science (File Handling & Pandas chapter).
1. Read a CSV File Using Pandas ⭐⭐⭐⭐⭐
(Very important)
Question: Write a program to read
data from a CSV file using Pandas.
import pandas as pd
# Reading CSV file
data =
pd.read_csv("student.csv")
# Display data
print(data)
Concepts covered:
- Import
Pandas
- read_csv()
- DataFrame
2. Write Data into a CSV File Using
Pandas ⭐⭐⭐⭐⭐
(Very important)
Question: Write a program to create
a DataFrame and save it into a CSV file.
import pandas as pd
data = {
"Name": ["Ram", "Hari", "Sita"],
"Age": [20, 21, 19],
"Grade": ["A", "B", "A"]
}
df = pd.DataFrame(data)
df.to_csv("student.csv",
index=False)
print("Data written
successfully")
Concepts covered:
- pd.DataFrame()
- to_csv()
- index=False
3. Read CSV File Using CSV Module ⭐⭐⭐⭐
Question: Write a program to read a
CSV file using the csv module.
import csv
with open("student.csv",
"r") as file:
csv_reader = csv.reader(file)
for row in csv_reader:
print(row)
Concepts covered:
- csv.reader()
- File
opening
- Reading
rows
4. Create a New File in Python ⭐⭐⭐⭐
Question: Write a program to create
a new file.
file =
open("example.txt", "x")
print("File created
successfully")
file.close()
Concepts covered:
- x
mode
- close()
5. Write Data into a Text File ⭐⭐⭐⭐⭐
Question: Write a program to write
data into a file.
file =
open("message.txt", "w")
file.write("Python file
handling")
file.close()
print("Data written
successfully")
Concepts covered:
- w
mode
- write()
6. Append Data into an Existing
File ⭐⭐⭐⭐⭐
Question: Write a program to add
new data to an existing file.
file =
open("message.txt", "a")
file.write("\nLearning Python
is easy")
file.close()
print("Data appended
successfully")
Concepts covered:
- a
mode
- Adding
data without deleting old content
7. Read a Text File ⭐⭐⭐⭐⭐
Question: Write a program to read
data from a file.
file =
open("message.txt", "r")
data = file.read()
print(data)
file.close()
Concepts covered:
- r
mode
- read()
8. Read Specific Number of
Characters using read(size) ⭐⭐⭐
file =
open("message.txt", "r")
data = file.read(10)
print(data)
file.close()
Concept:
- Reads
only specified characters.
9. Read File Line by Line ⭐⭐⭐⭐
file =
open("message.txt", "r")
print(file.readline())
file.close()
Concept:
- readline()
reads one line.
10. Display First 5 Rows of CSV
File Using Pandas ⭐⭐⭐⭐⭐
Question: Write a program to
display first five records from CSV file.
import pandas as pd
df =
pd.read_csv("student.csv")
print(df.head())
Concept:
- head()
displays first 5 rows.
11. Calculate Average from CSV Data
Using Pandas ⭐⭐⭐⭐⭐
Question: Find the average value
from CSV data.
import pandas as pd
df =
pd.read_csv("student.csv")
average =
df["Age"].mean()
print("Average Age:",
average)
Concepts:
- Selecting
column
- mean()
12. Filter Data from CSV File ⭐⭐⭐⭐⭐
Question: Display only students
having Grade A.
import pandas as pd
df =
pd.read_csv("student.csv")
result = df[df["Grade"]
== "A"]
print(result)
Concept:
- Data
filtering in Pandas
13. Access Column from DataFrame ⭐⭐⭐⭐
import pandas as pd
df =
pd.read_csv("student.csv")
print(df.Name)
or
print(df["Name"])
A. Basic File Handling Programs
(Python)
✅ 1. Open and Read a File (read()) ⭐⭐⭐⭐⭐
file = open("Test.txt",
"r")
data = file.read()
print(data)
file.close()
✅ 2. Read Specific Characters
(read(size)) ⭐⭐⭐⭐
file = open("Test.txt",
"r")
data = file.read(10)
print(data)
file.close()
✅ 3. Read First Line (readline()) ⭐⭐⭐⭐
file = open("Test.txt",
"r")
line = file.readline()
print(line)
file.close()
✅ 4. Read All Lines (readlines()) ⭐⭐⭐⭐
file = open("Test.txt",
"r")
lines = file.readlines()
print(lines)
file.close()
✅ 5. Create a New File using x Mode ⭐⭐⭐⭐
file =
open("newfile.txt", "x")
print("File created")
file.close()
✅ 6. Create/Write File using w Mode ⭐⭐⭐⭐⭐
file = open("Test.txt",
"w")
file.write("Hello
Python")
file.close()
✅ 7. Write Multiple Lines using
write() ⭐⭐⭐⭐
with open("file.txt",
"w") as file:
file.write("First line\n")
file.write("Second line\n")
file.write("Third line")
✅ 8. Write Multiple Strings using
writelines() ⭐⭐⭐⭐
file = open("file.txt",
"w")
file.writelines([
"First line\n",
"Second line\n",
"Third line"
])
file.close()
✅ 9. Append Data using a Mode ⭐⭐⭐⭐⭐
file = open("Test.txt",
"a")
file.write("\nNew data
added")
file.close()
✅ 10. Close a File ⭐⭐⭐
file = open("Test.txt",
"r")
print(file.read())
file.close()
B. CSV Module Programs
✅ 11. Read CSV File Using
csv.reader() ⭐⭐⭐⭐⭐
import csv
with open("data.csv",
"r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
✅ 12. Write CSV File Using CSV
Module ⭐⭐⭐⭐
(Not shown in your text but related
to CSV handling)
import csv
with open("student.csv",
"w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age"])
writer.writerow(["Ram", 20])
C. Pandas CSV Programs
✅ 13. Import Pandas Library ⭐⭐⭐
import pandas as pd
✅ 14. Read CSV Using Pandas
(read_csv()) ⭐⭐⭐⭐⭐
import pandas as pd
df =
pd.read_csv("student.csv")
print(df)
✅ 15. Display Column Names (columns)
⭐⭐⭐⭐
print(df.columns)
✅ 16. Access Specific Column ⭐⭐⭐⭐
print(df.Name)
or
print(df["Name"])
✅ 17. Display First 5 Rows (head()) ⭐⭐⭐⭐⭐
print(df.head())
✅ 18. Create DataFrame using
Dictionary ⭐⭐⭐⭐⭐
import pandas as pd
data = {
"Name":["Ram","Hari"],
"Age":[20,21]
}
df = pd.DataFrame(data)
print(df)
✅ 19. Write DataFrame to CSV
(to_csv()) ⭐⭐⭐⭐⭐
import pandas as pd
data = {
"Name":["Ram","Hari"],
"Age":[20,21]
}
df = pd.DataFrame(data)
df.to_csv("student.csv",
index=False)
✅ 20. Write Real-Life Product Data
to CSV ⭐⭐⭐⭐
import pandas as pd
data = {
"Product":["Laptop","Mobile","Tablet"],
"Price":[75000,15000,20000],
"Quantity":[3,10,5]
}
df = pd.DataFrame(data)
df.to_csv("products.csv",
index=False)
✅ 21. Calculate Average from CSV
Data ⭐⭐⭐⭐⭐
import pandas as pd
df =
pd.read_csv("student.csv")
average =
df["Age"].mean()
print(average)
✅ 22. Filter Data from CSV (Grade A
Students) ⭐⭐⭐⭐⭐
import pandas as pd
df =
pd.read_csv("student.csv")
result =
df[df["Grade"]=="A"]
print(result)
4.7 Introduction to Data
Visualization
Data visualization is the process
of representing data using charts, graphs, and visual diagrams so that
information can be understood easily. It helps us see patterns, trends, and
connections in a simple way.
Python provides many powerful
libraries for creating simple and advanced visualizations. Some popular tools
used for data visualization are Matplotlib, Seaborn, and Plotly.
Importance of Data Visualization
Data visualization is important
because it helps people understand large amounts of data quickly and easily by
turning it into charts and graphs. This makes it easier to see trends,
patterns, and new ideas.
Today, businesses and professionals
use data to make better decisions. Since a huge amount of data is created every
day, visualization helps us make sense of it and share our ideas clearly
Popular Python Libraries for Data
Visualization
i. Matplotlib
- Matplotlib
is a popular Python library used for simple graphs like bar charts, bar
charts and line graphs..
ii. Seaborn
- Seaborn
is a Python library used to create beautiful and colorful charts easily.
iii. Plotly
- Plotly
is a Python library used to create interactive and dynamic graphs.
Matplotlib
Matplotlib is the most popular Python library
used for data visualization and plotting graphs. It is a low-level
plotting library that provides a Matlab-like interface and gives users a
lot of control over graph design.
Since Matplotlib provides many
options, users may need to write more code compared to other libraries.
Matplotlib is specifically suitable
for creating basic graphs like line charts, bar charts, histograms, etc.
Installing Matplotlib
Matplotlib can be installed using pip
or conda through the command prompt.
pip install matplotlib
or
conda install matplotlib
Importing Matplotlib
import matplotlib.pyplot as plt
Here, pyplot is a module of
Matplotlib that provides functions for creating graphs.
Features of Matplotlib
- Used
for creating basic graphs.
- Provides
control over graph appearance.
- Supports
different types of charts such as:
- Line
charts
- Bar
charts
- Histograms
- Scatter
plots
- Pie
charts
1. Scatter Plot
A scatter plot uses dots to
represent the relationship between two variables. It helps observe patterns and
connections between data values.
Matplotlib provides the scatter()
method to create scatter plots.
Syntax:
plt.scatter(x, y)
Example:
# Importing libraries
import pandas as pda
import matplotlib.pyplot as plt
# Reading the dataset
dataset =
pda.read_csv("Stu_data.csv")
# Creating scatter plot
plt.scatter(dataset['Name'],
dataset['Marks'])
# Adding title and labels
plt.title("Scatter Plot")
plt.xlabel('Name')
plt.ylabel('Marks')
# Display graph
plt.show()
2. Bar Chart
A bar chart represents data
categories using rectangular bars. The height or length of each bar represents
the value of the data.
Bar charts are useful for comparing
different categories.
Matplotlib provides the bar()
method to create bar charts.
Syntax:
plt.bar(x, y)
Example:
# Importing libraries
import pandas as pda
import matplotlib.pyplot as plt
# Reading the database
data =
pda.read_csv("tips.csv")
# Creating bar chart
plt.bar(data['total_bill'],
data['day'])
# Adding title and labels
plt.title("Bar Chart")
plt.xlabel('Day')
plt.ylabel('Tip')
# Display graph
plt.show()
Difference Between Scatter Plot and
Bar Chart
|
Scatter Plot |
Bar Chart |
|
Uses dots to represent data |
Uses rectangular bars |
|
Shows relationship between
variables |
Compares different categories |
|
Created using scatter() method |
Created using bar() method |
|
Useful for finding patterns |
Useful for comparing values |
In conclusion, Matplotlib is a
powerful Python library that helps convert data into meaningful visual graphs,
making data analysis easier and more understandable.
Seaborn
Introduction
Seaborn is a Python library used to create
beautiful, attractive, and informative charts. It is built on top of Matplotlib
and works well with Pandas data.
Seaborn is mainly used to visualize
patterns, relationships, and trends in data. It can create complex
charts with fewer lines of code.
Features of Seaborn
Seaborn is useful for creating
different types of charts such as:
- Line
Plot
- Shows
changes or trends in data over time.
- Bar
Plot
- Compares
values between different categories.
- Heatmap
- Uses
colors to represent data values and relationships.
Installing Seaborn
Seaborn can be installed using the
command prompt:
pip install Seaborn
It works best in environments like Jupyter
Notebook or IPython, where graphs can be displayed clearly.
Line Plot in Seaborn
Meaning
A line plot is used to show
the relationship between two variables using a connected line.
Seaborn provides the lineplot()
method to create line plots.
Syntax:
sn.lineplot(x='column1',
y='column2', data=dataset)
Example:
# Importing libraries
import pandas as pda
import seaborn as sn
import matplotlib.pyplot as plt
# Reading the database
dataset =
pda.read_csv("Stu_data.csv")
# Creating line plot
sn.lineplot(x='Name', y='Marks',
data=dataset)
# Display graph
plt.show()
Plotly
Introduction
Plotly is an open-source Python library
used to create interactive charts and graphs.
Unlike simple graphs, Plotly allows
users to:
- Zoom
into graphs
- Hover
over data points
- Edit
and explore charts easily
Plotly graphs can be viewed in:
- Jupyter
Notebook
- Web
browsers
- HTML
files
Types of Graphs Created Using
Plotly
Plotly can create:
- 3D
Charts
- Scientific
and Statistical Charts
- Financial
Charts
- Scatter
Plots
- Line
Charts
- Bar
Charts
Installing Plotly
Plotly can be installed using:
pip install plotly
1. Scatter Plot in Plotly
Meaning
A scatter plot represents the
relationship between two variables using points.
Plotly uses the scatter()
method to create scatter plots.
Example:
import pandas as pda
import plotly.express
# Reading CSV dataset
dataset =
pda.read_csv("tips.csv")
# Creating scatter plot
graph = plotly.express.scatter(
dataset,
x="total_bill",
y="size",
color="smoker"
)
# Display graph
graph.show()
2. Line Chart in Plotly
A line chart connects data points
with lines to show patterns and changes.
Plotly uses the line()
method to create line charts.
Example:
# Importing libraries
import plotly.express as px
import pandas as pda
# Reading database
data =
pda.read_csv("Stu_data.csv")
# Creating line chart
fig = px.line(data, y='Name',
color='Gender')
# Showing graph
fig.show()
Output:
A line chart showing data based on
student names and gender.
3. Bar Chart in Plotly
Meaning
A bar chart uses rectangular bars
to compare values between categories.
Plotly uses the bar() method
to create bar charts.
Example:
# Importing libraries
import plotly.express as px
import pandas as pd
# Reading database
data =
pd.read_csv("Stu_data.csv")
# Creating bar chart
fig = px.bar(
data,
x='Name',
y='Marks',
color='Gender'
)
# Display graph
fig.show()
Output:
A bar chart showing students' marks
with different colors based on gender.
Difference Between Matplotlib,
Seaborn, and Plotly
|
Library |
Main Feature |
Best Used For |
|
Matplotlib |
Basic and customizable graphs |
Line charts, bar charts,
histograms |
|
Seaborn |
Beautiful statistical charts |
Pattern and relationship analysis |
|
Plotly |
Interactive graphs |
Dashboards and dynamic
visualization |
Summary:
Python libraries like Matplotlib, Seaborn, and Plotly make data
visualization easier by converting raw data into meaningful graphs and charts. 📊
A. Solved Examples (Full Python
Programs)
1. Create a New Text File and Write
Content
# Create a new file and write
content
file =
open("example.txt", "w")
file.write("Hello, this is a
new file created using Python file handling.")
file.close()
print("File created and
content written successfully.")
2. Append New Content to Existing
File
# Append content to a file
file =
open("example.txt", "a")
file.write("\nThis is an
appended line.")
file.close()
print("New content appended
successfully.")
3. Read Content from a File
# Read content from file
file =
open("example.txt", "r")
content = file.read()
print("File content:\n",
content)
file.close()
4. Read First 10 Characters of File
# Read first 10 characters
file =
open("example.txt", "r")
print("First 10
characters:", file.read(10))
file.close()
5. Read CSV File Using Pandas
import pandas as pd
df =
pd.read_csv("sample_data.csv")
print(df)
6. Count Number of Rows in CSV File
import pandas as pd
df =
pd.read_csv("sample_data.csv")
print("Number of rows:",
len(df))
7. Pie Chart Using Matplotlib
import matplotlib.pyplot as plt
labels = ['A', 'B', 'C', 'D']
sizes = [20, 30, 25, 25]
plt.pie(
sizes,
labels=labels,
autopct='%1.1f%%'
)
plt.title("Pie Chart
Example")
plt.show()
8. Bar Chart Using Plotly
import plotly.express as px
import pandas as pd
data = pd.DataFrame(
{
'Category':['A','B','C','D'],
'Value':[10,20,30,40]
}
)
fig = px.bar(
data,
x='Category',
y='Value',
title="Bar Chart Example"
)
fig.show()
9. Save DataFrame as CSV File
import pandas as pd
data = {
'Product':['Laptop','Phone','Tablet'],
'Price':[700,300,200],
'Stock':[50,100,80]
}
df = pd.DataFrame(data)
df.to_csv(
'products.csv',
index=False
)
print("Data saved to
products.csv successfully.")
I will continue next with:
Part 2: Code Practice Programs
(Full Python Programs) 💻
(From the uploaded Class 10
Computer Science file)
1. Program to Find Greater of Two
Numbers
# Ask for two numbers from the user
num1 = float(input("Enter the
first number: "))
num2 = float(input("Enter the
second number: "))
# Compare and display greater
number
if num1 > num2:
print("The greater number is:", num1)
elif num2 > num1:
print("The greater number is:", num2)
else:
print("Both numbers are equal.")
2. Program to Calculate Area and
Volume of Room
Formula:
- Area
= Length × Breadth
- Volume
= Length × Breadth × Height
# Function to calculate area of
floor
def calculate_area(length,
breadth):
return length * breadth
# Function to calculate volume
def calculate_volume(length,
breadth, height):
return length * breadth * height
# Taking input from user
length = float(input("Enter
the length of the room (in meters): "))
breadth = float(input("Enter
the breadth of the room (in meters): "))
height = float(input("Enter
the height of the room (in meters): "))
# Calculating results
area = calculate_area(length,
breadth)
volume = calculate_volume(length,
breadth, height)
# Displaying results
print("Area of the
floor:", area, "square meters")
print("Volume of the
room:", volume, "cubic meters")
3. Convert Feet into Inches
Formula:
1 foot = 12 inches
# Function to convert feet into
inches
def feet_to_inches(feet):
return feet * 12
# Taking input
feet = float(input("Enter the
length in feet: "))
# Conversion
inches = feet_to_inches(feet)
# Display result
print("Length in
inches:", inches)
4. Product and Average of Three
Numbers
# Function to calculate product
def find_product(a, b, c):
return a * b * c
# Subprogram to calculate average
def show_average(x, y, z):
average = (x + y + z) / 3
print("The average is", average)
# Taking input
num1 = float(input("Enter
first number: "))
num2 = float(input("Enter
second number: "))
num3 = float(input("Enter
third number: "))
# Calling functions
product = find_product(num1, num2,
num3)
print("The product is",
product)
show_average(num1, num2, num3)
5. Area of Square Using Function
Formula:
Area = Side × Side
# Function to calculate area
def find_area(side):
area = side * side
return area
# Input
side_length =
float(input("Enter the side length of the square: "))
# Function call
area = find_area(side_length)
# Display result
print("The area of the square
is", area)
6. Total Surface Area of Cuboid
Formula:
TSA = 2(lb + bh + hl)
# Function to calculate TSA of
cuboid
def total_surface_area(length,
breadth, height):
tsa = 2 * (
length * breadth +
breadth * height +
height * length
)
return tsa
# Input
l = float(input("Enter the
length of the cuboid: "))
b = float(input("Enter the
breadth of the cuboid: "))
h = float(input("Enter the
height of the cuboid: "))
# Function call
tsa = total_surface_area(l, b, h)
# Output
print("The Total Surface Area
of the cuboid is", tsa)
7. Perimeter of Square Using
Subprogram
Formula:
Perimeter = 4 × L
# Subprogram to calculate perimeter
def show_perimeter(side):
perimeter = 4 * side
print("The perimeter of the square is", perimeter)
# Input
side_length =
float(input("Enter the side length of the square: "))
# Calling subprogram
show_perimeter(side_length)
I will continue with Part 3
next:
Part 3: Code Practice Programs
(Full Python Programs) 💻
(From the uploaded Class 10
Computer Science file)
8. Program to Calculate
Circumference of Circle
Formula:
Circumference = 2πr
import math
# Subprogram to calculate
circumference
def show_circumference(radius):
circumference = 2 * math.pi * radius
print("The circumference of the circle is", circumference)
# Taking input
r = float(input("Enter the
radius of the circle: "))
# Calling subprogram
show_circumference(r)
9. Program to Calculate Total
Surface Area of Sphere
Formula:
TSA = 4πr²
import math
# Subprogram to calculate surface
area
def show_surface_area(radius):
tsa = 4 * math.pi * radius * radius
print("The Total Surface Area of the sphere is", tsa)
# Taking input
r = float(input("Enter the
radius of the sphere: "))
# Calling subprogram
show_surface_area(r)
10. Program to Calculate Curved
Surface Area of Cuboid
Formula:
CSA = 2h(l+b)
# Subprogram to calculate CSA
def show_csa(length, breadth,
height):
csa = 2 * height * (length + breadth)
print("The Curved Surface Area of the cuboid is", csa)
# Taking input
l = float(input("Enter the
length of the cuboid: "))
b = float(input("Enter the
breadth of the cuboid: "))
h = float(input("Enter the
height of the cuboid: "))
# Calling subprogram
show_csa(l, b, h)
11. Generate Series and Calculate
Sum
Series:
2, 3, 5, 8, 13, 21, 34
# Initialize first two terms
a = 2
b = 3
total = a + b
print("Series:")
print(a, b, end=" ")
# Generate remaining terms
for i in range(8):
next_term = a + b
print(next_term, end=" ")
total += next_term
a = b
b = next_term
# Display sum
print("\nSum of the series
is:", total)
12. Find Sum of Digits of a Number
Example:
Input: 123
Output: 6
# Function to find sum of digits
def sum_of_digits(num):
total = 0
while num > 0:
digit = num % 10
total = total + digit
num = num // 10
return total
# Input
number = int(input("Enter a
number: "))
# Function call
result = sum_of_digits(number)
# Output
print("Sum of digits
is:", result)
13. Display Multiplication Table
Using Function
# Function to display
multiplication table
def show_table(num):
print("Multiplication Table of", num)
for i in range(1, 11):
print(num, "x", i,
"=", num * i)
# Input
number = int(input("Enter a
number: "))
# Function call
show_table(number)
14. Find Factorial Using User
Defined Function
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
# Function to calculate factorial
def find_factorial(n):
fact = 1
for i in range(1, n + 1):
fact = fact * i
return fact
# Input
number = int(input("Enter a
number: "))
# Function call
result = find_factorial(number)
# Display result
print("Factorial of",
number, "is", result)
15. Create a File and Store Student
Details
Creates student.txt and
stores name and class of 3 students.
file =
open("student.txt", "w")
for i in range(3):
name = input("Enter name of student: ")
clas = input("Enter class of student: ")
file.write(name + "," + clas + "\n")
file.close()
print("Data written to
student.txt")
16. Read and Display Student File
file =
open("student.txt", "r")
print("Contents of
student.txt:")
for line in file:
print(line.strip())
file.close()
Next Part 4 will include the
remaining important programs:
Part 4: Code Practice Programs
(Full Python Programs) 💻
(From the uploaded Class 10
Computer Science file)
17. Add (Append) One More Student
to Existing File
Concept: Append mode (a) adds new data
without deleting existing data.
# Open file in append mode
file =
open("student.txt", "a")
# Input new student details
name = input("Enter name of
new student: ")
clas = input("Enter class of
new student: ")
# Write data
file.write(name + "," +
clas + "\n")
# Close file
file.close()
print("Data added to
student.txt")
18. Generate Series Using Function
and Calculate Sum
Series:
2 3 5 8 13 21 34
# Function to generate series
def generate_series(n):
series = [2, 3]
for i in range(2, n):
next_number = series[i-1] + series[i-2]
series.append(next_number)
return series
# Number of terms
terms = 10
# Generate series
series = generate_series(terms)
# Calculate sum
series_sum = sum(series)
# Display output
print("Generated
Series:")
print(series)
print("Sum of the
series:", series_sum)
19. Calculate Sum, Product and
Difference Using Separate Functions
# Function to calculate sum
def find_sum(a, b):
return a + b
# Function to calculate product
def find_product(a, b):
return a * b
# Function to calculate difference
def find_difference(a, b):
return a - b
# Input numbers
num1 = float(input("Enter the
first number: "))
num2 = float(input("Enter the
second number: "))
# Calculations
sum_result = find_sum(num1, num2)
product_result = find_product(num1,
num2)
difference_result =
find_difference(num1, num2)
# Display results
print("Sum:", sum_result)
print("Product:",
product_result)
print("Difference:",
difference_result)
20. Display Employees with Salary
More Than 75,000
File: employee.csv
Fields:
- Name
- Address
- Gender
- Salary
import pandas as pd
# Read CSV file
df =
pd.read_csv("employee.csv")
# Filter salary greater than 75000
high_salary_df = df[df['Salary']
> 75000]
# Display records
print("Employees with salary
more than 75,000:")
print(high_salary_df)
21. Display Male Students with
Computer Marks More Than 85
File: result.csv
Conditions:
- Gender
= M
- Computer
marks > 85
import pandas as pd
# Read CSV file
df =
pd.read_csv("result.csv")
# Filter records
filtered_df = df[
(df['Gender'] == 'M') &
(df['Computer'] > 85)
]
# Display records
print("Students with Gender
'M' and Computer marks > 85:")
print(filtered_df)
22. Display Employees with Salary
More Than 50,000
import pandas as pd
# Read CSV file
df =
pd.read_csv("employee.csv")
# Filter employees
high_salary_df = df[df['Salary']
> 50000]
# Display output
print("Employees with salary
more than 50,000:")
print(high_salary_df)
23. Display Female Students with
Computer Marks More Than 90
Conditions:
- Gender
= F
- Computer
marks > 90
import pandas as pd
# Read CSV file
df =
pd.read_csv("record.csv")
# Filter records
filtered_df = df[
(df['Gender'] == 'F') &
(df['Computer'] > 90)
]
# Display result
print("Female students who
scored more than 90 in Computer:")
print(filtered_df)
✅ Completed all 23 Python Code
Practice Programs from the file. 📘
Sure 👍 I will format the MCQs with options
in a single row like exam paper style.
1. Choose the Correct Answer
i. What is the primary goal of data
visualization?
a) To store data efficiently. b)
To perform complex calculations on data. c) To understand data through
visual context. d) To secure data from unauthorized access.
✅ Answer:
c) To understand data through visual context
ii. Which of the following is a
popular Python library for creating basic graphs like line charts and bar
charts?
a) Seaborn b) Plotly c)
Matplotlib d) Pandas
✅ Answer:
c) Matplotlib
iii. Which type of plot uses dots
to represent relationships between variables?
a) Bar chart b) Line chart c)
Scatter plot d) Pie plot
✅ Answer:
c) Scatter plot
iv. What type of chart uses
rectangular bars to represent data categories?
a) Scatter plot b) Line chart c)
Bar chart d) Pie plot
✅ Answer:
c) Bar chart
v. Which data visualization library
in Python is built on Matplotlib and offers more advanced statistical
visualizations?
a) Plotly b) Pandas c) Seaborn
d) GGPlot
✅ Answer:
c) Seaborn
vi. Which Plotly method is used to
create a scatter plot?
a) scatter() b) line() c) bar() d) pie()
✅ Answer:
a) scatter()
vii. Which Plotly Express function
is used to create a line chart?
a) px.scatter() b) px.line()
c) px.bar() d) px.pie()
✅ Answer:
b) px.line()
viii. Which Matplotlib function is
commonly used to create a pie chart?
a) plt.scatter() b) plt.plot() c)
plt.bar() d) plt.pie()
✅ Answer:
d) plt.pie()
ix. Which Plotly Express function
is used to create a bar chart?
a) px.scatter() b) px.line() c)
px.bar() d) px.histogram()
✅ Answer:
c) px.bar()
2. Short Answer Questions
a) Define data visualization in
your own words.
Answer:
Data visualization is the process of representing data using charts, graphs,
and visual elements to make information easier to understand. It helps identify
patterns, trends, and relationships in data.
b) Why is data visualization
important for businesses and analysts?
Answer:
Data visualization helps businesses and analysts understand large amounts of
data quickly. It helps find trends, make better decisions, and communicate
information clearly.
c) Name three popular Python
libraries for data visualization.
Answer:
The three popular Python libraries are:
- Matplotlib
- Seaborn
- Plotly
d) What is the key characteristic
of Matplotlib that offers both freedom and the need for more code?
Answer:
Matplotlib is a low-level plotting library that provides high customization and
control over graphs, but it requires writing more code.
e) What type of data is typically
represented using a bar chart?
Answer:
Bar charts are used to represent categorical data and compare values
between different categories.
f) What is Seaborn built upon, and
what type of visualizations does it focus on?
Answer:
Seaborn is built on top of Matplotlib and focuses mainly on statistical
visualizations and showing relationships between data.
g) What is a key feature of Plotly
that distinguishes it from Matplotlib?
Answer:
The key feature of Plotly is that it creates interactive and dynamic graphs
where users can zoom, hover, and explore data.
h) In Matplotlib, what is the role
of plt.xlabel() and plt.ylabel()?
Answer:
plt.xlabel() is used to label the x-axis, and plt.ylabel() is used to label the
y-axis of a graph.
i) What type of data is best
represented using a pie plot?
Answer:
A pie plot is best used for showing percentage contribution or proportion of
different categories in a whole dataset.
j) What is the purpose of the color
argument in Plotly Express functions?
Answer:
The color argument is used to differentiate data categories by applying
different colors to data points or bars.
Part 2: Long Answers + Python
Programs (Practical Questions) 💻📚
3. Long Answer Questions
i. Explain the importance of data
visualization in the process of data analysis.
Answer:
Data visualization is the process
of representing data using charts, graphs, and visual elements to make it
easier to understand. It plays an important role in data analysis because it
converts complex data into simple and meaningful information.
Importance of Data Visualization:
- Easy
Understanding
- Visualization
helps users understand large amounts of data quickly by presenting it in
graphical form.
- Finding
Patterns and Trends
- Charts
and graphs help identify hidden patterns, trends, and relationships in
data.
- Better
Decision Making
- Organizations
use visualized data to make accurate and effective decisions.
- Data
Comparison
- Graphs
allow easy comparison between different categories or groups.
- Quick
Analysis
- Visual
information can be understood faster than reading large tables of
numbers.
- Clear
Communication
- It
helps present data clearly to others through reports and presentations.
Therefore, data visualization is an
important part of data analysis because it helps transform raw data into useful
information.
ii. Compare Matplotlib and Plotly
for Data Visualization in Python.
|
Feature |
Matplotlib |
Plotly |
|
Type |
Low-level plotting library |
Interactive visualization library |
|
Ease of Use |
Requires more code |
Easier for interactive charts |
|
Customization |
Provides high customization |
Provides attractive default
styles |
|
Interactivity |
Limited interaction |
Highly interactive |
|
Output |
Static graphs |
Interactive graphs |
|
Best Use |
Basic graphs and scientific
plotting |
Dashboards and interactive
reports |
Matplotlib
- Matplotlib
is a popular Python plotting library.
- It
is suitable for creating:
- Line
charts
- Bar
charts
- Pie
charts
- Histograms
- It
provides complete control over graph design but requires more programming.
Plotly
- Plotly
is an open-source library used for interactive charts.
- Users
can:
- Zoom
graphs
- Hover
over data points
- Explore
information
- It
is useful for modern dashboards and dynamic visualization.
Conclusion
Matplotlib is suitable for simple
and highly customized graphs, whereas Plotly is better for interactive and
user-friendly visualizations.
iii. Explain how to create Line
Chart, Bar Chart, and Pie Chart using Matplotlib.
1. Import Matplotlib Library
import matplotlib.pyplot as plt
Line Chart
A line chart represents changes or
trends in data.
import matplotlib.pyplot as plt
x = [1,2,3,4]
y = [10,20,30,40]
plt.plot(x,y)
plt.title("Line Chart")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()
Bar Chart
A bar chart represents data
categories using rectangular bars.
import matplotlib.pyplot as plt
category = ['A','B','C']
value = [20,40,30]
plt.bar(category,value)
plt.title("Bar Chart")
plt.xlabel("Category")
plt.ylabel("Value")
plt.show()
Pie Chart
A pie chart shows percentage
contribution of different categories.
import matplotlib.pyplot as plt
labels = ['A','B','C']
sizes = [30,40,30]
plt.pie(
sizes,
labels=labels
)
plt.title("Pie Chart")
plt.show()
iv. Sales Data Visualization Using
Pandas and Matplotlib
Suppose DataFrame contains:
- Month
- Category
- Sales
a) Line Chart Showing Total Sales
Trend
Steps:
- Read
CSV file.
- Group
sales according to month.
- Create
line chart.
import pandas as pd
import matplotlib.pyplot as plt
data =
pd.read_csv("sales.csv")
monthly_sales = data.groupby(
"Month"
)["Sales"].sum()
plt.plot(
monthly_sales.index,
monthly_sales.values
)
plt.title("Monthly Sales
Trend")
plt.xlabel("Month")
plt.ylabel("Sales")
plt.show()
b) Bar Graph Comparing Product
Categories
import pandas as pd
import matplotlib.pyplot as plt
data =
pd.read_csv("sales.csv")
category_sales = data.groupby(
"Category"
)["Sales"].sum()
plt.bar(
category_sales.index,
category_sales.values
)
plt.title("Category
Sales")
plt.xlabel("Category")
plt.ylabel("Sales")
plt.show()
c) Pie Chart Showing Category
Contribution
import pandas as pd
import matplotlib.pyplot as plt
data =
pd.read_csv("sales.csv")
category_sales = data.groupby(
"Category"
)["Sales"].sum()
plt.pie(
category_sales.values,
labels=category_sales.index,
autopct="%1.1f%%"
)
plt.title("Sales
Contribution")
plt.show()
Part 3 will continue with Practical
Questions (18 Python Programs) 💻📘
Part 3: Practical Questions – Full
Python Programs 💻📚
(From Exercise: Data Visualization
& Python Programming)
i. Program to Input Two Numbers and
Print Sum, Difference, Product, and Quotient
# Taking input from user
num1 = float(input("Enter
first number: "))
num2 = float(input("Enter
second number: "))
# Calculations
sum_result = num1 + num2
difference = num1 - num2
product = num1 * num2
quotient = num1 / num2
# Display results
print("Sum =",
sum_result)
print("Difference =",
difference)
print("Product =",
product)
print("Quotient =",
quotient)
ii. Program to Take User Name and
Print Greeting Message
# Taking name input
name = input("Enter your name:
")
# Printing greeting
print("Hello", name,
"Welcome to Python Programming!")
iii. Check Whether Number is
Positive, Negative, or Zero
# Taking input
number = int(input("Enter a
number: "))
# Checking condition
if number > 0:
print("The number is positive")
elif number < 0:
print("The number is negative")
else:
print("The number is zero")
iv. Swap Two Numbers Without Using
Third Variable
# Input numbers
a = int(input("Enter first
number: "))
b = int(input("Enter second
number: "))
# Swapping
a, b = b, a
# Display result
print("After swapping:")
print("First number =",
a)
print("Second number =",
b)
v. Count Number of Vowels in a
Sentence
# Input sentence
sentence = input("Enter a
sentence: ")
count = 0
# Checking vowels
for ch in sentence:
if ch.lower() in "aeiou":
count = count + 1
# Display result
print("Number of
vowels:", count)
vi. Create File
"data.txt" and Write Content
# Creating file
file = open("data.txt",
"w")
# Writing content
file.write("Hello, this is a
test file.")
# Closing file
file.close()
print("File created
successfully.")
vii. Append Content to Existing
File
# Opening file in append mode
file = open("data.txt",
"a")
# Adding new line
file.write("\nThis is an
appended line.")
# Closing file
file.close()
print("Content appended
successfully.")
viii. Read File and Print Content
# Opening file
file = open("data.txt",
"r")
# Reading content
content = file.read()
# Display content
print(content)
# Closing file
file.close()
ix. Create CSV File Using csv
Module
Creates students.csv with
columns:
- Name
- Marks
import csv
# Opening CSV file
file =
open("students.csv", "w", newline="")
writer = csv.writer(file)
# Writing header
writer.writerow(["Name",
"Marks"])
# Adding student records
writer.writerow(["Ram",
85])
writer.writerow(["Sita",
90])
writer.writerow(["Hari",
78])
# Closing file
file.close()
print("CSV file created
successfully.")
x. Read Data from students.csv
import csv
# Opening file
file =
open("students.csv", "r")
reader = csv.reader(file)
# Display records
for row in reader:
print(row)
file.close()
Part 4: Practical Questions – Full
Python Programs 💻📚
(Continuation)
xi. Using Pandas, Read a CSV File
and Print First Five Rows
Program:
import pandas as pd
# Reading CSV file
data =
pd.read_csv("student.csv")
# Display first five rows
print(data.head())
Explanation:
- read_csv()
is used to read CSV files.
- head()
displays the first five records of the DataFrame.
xii. Create a DataFrame from
Dictionary and Save it as CSV
import pandas as pd
# Creating dictionary
data = {
"Name": ["Ram", "Sita", "Hari"],
"Marks": [85, 90, 78],
"Grade": ["A", "A+", "B"]
}
# Creating DataFrame
df = pd.DataFrame(data)
# Saving DataFrame as CSV
df.to_csv("students.csv",
index=False)
print("Data saved
successfully.")
Output File:
students.csv
xiii. Read CSV Data and Plot Pie
Chart Using Pandas and Matplotlib
import pandas as pd
import matplotlib.pyplot as plt
# Reading CSV file
data =
pd.read_csv("product.csv")
# Creating pie chart
plt.pie(
data["Sales"],
labels=data["Product"],
autopct="%1.1f%%"
)
plt.title("Product
Sales")
plt.show()
Explanation:
- Pandas
reads the CSV data.
- Matplotlib
creates the pie chart.
- Pie
chart shows percentage contribution of each product.
xiv. Function to Return Sum of Two
Numbers
# Function definition
def add_numbers(a, b):
return a + b
# Input
num1 = int(input("Enter first
number: "))
num2 = int(input("Enter second
number: "))
# Function call
result = add_numbers(num1, num2)
# Display output
print("Sum =", result)
xv. Function to Calculate Area of
Circle
Formula:
Area = π × r²
import math
# Function definition
def area_circle(radius):
area = math.pi * radius * radius
return area
# Input
r = float(input("Enter radius
of circle: "))
# Function call
result = area_circle(r)
# Output
print("Area of circle =",
result)
xvi. Function to Check Whether
Number is Prime or Not
# Function to check prime number
def check_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
# Input
num = int(input("Enter a
number: "))
# Checking result
if check_prime(num):
print("Number is prime")
else:
print("Number is not prime")
xvii. Function to Find Maximum
Number from a List
# Function to find maximum number
def find_max(numbers):
maximum = numbers[0]
for num in numbers:
if num > maximum:
maximum = num
return maximum
# Input list
numbers = [10, 25, 5, 40, 15]
# Function call
result = find_max(numbers)
# Display output
print("Maximum number
is:", result)
xviii. Read File and Handle
Exception if File Does Not Exist
try:
file = open("data.txt", "r")
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print("File does not exist.")
✅ Completed All Practical Questions
(i–xviii)
Project Work
Develop a Simple Python Project
Using Libraries, User Defined Functions, and Visualization Tools
Class 10 Computer Science – Project
Report Format
Project Title:
Student Performance Analysis System
Using Python
1. Introduction
Python is a popular programming
language used for developing different types of applications. Python provides
many built-in and external libraries that help in data processing, calculation,
and visualization.
In this project, a Student
Performance Analysis System is developed using Python. The project collects
student marks, calculates total and average marks, determines grades, and
displays the performance using graphical visualization.
2. Objective
The main objectives of this project
are:
- To
understand the use of Python libraries.
- To
create and use user-defined functions.
- To
analyze student data using Python.
- To
represent data visually using charts.
- To
improve programming and problem-solving skills.
3. Software and Tools Used
Programming Language: Python
Platform Used:
- PyCharm
/ Jupyter Notebook / Google Colab
Libraries Used:
- Matplotlib – Used for creating graphs
and visualizations.
- Pandas – Used for organizing and
analyzing data.
4. Project Features
The project performs the following
tasks:
- Accepts
student names and marks.
- Calculates
total marks.
- Calculates
average marks.
- Assigns
grades.
- Displays
student performance.
- Creates
a bar chart for visualization.
5. Python Program Code
import pandas as pd# Calculate
resultsresult = []for i in range(len(students)): total = sum(marks[i]) average = total / 3 grade = calculate_grade(average) result.append([students[i], total,
average, grade])# Create DataFramedf = pd.DataFrame( result,
columns=["Name", "Total Marks", "Average",
"Grade"])print(df)# Visualizationplt.bar(df["Name"],
df["Average"])plt.xlabel("Students")plt.ylabel("Average
Marks")plt.title("Student Performance Analysis")plt.show()
6. Working Process / Methodology
Step 1: Planning
The project idea was selected and
the required features were identified.
Step 2: Data Collection
Sample student names and marks were
prepared as input data.
Step 3: Programming
Python code was written using:
- Variables
- Loops
- Conditional
statements
- User-defined
functions
Step 4: Library Implementation
Python libraries were used:
- Pandas
for data handling
- Matplotlib
for visualization
Step 5: Testing
The program was executed and
checked for correct calculations and output.
Step 6: Visualization
A bar graph was created to
represent student performance visually.
7. Output
Student Performance Table:
|
Name |
Total Marks |
Average |
Grade |
|
Ram |
253 |
84.33 |
A |
|
Sita |
225 |
75.00 |
B |
|
Hari |
180 |
60.00 |
B |
|
Gita |
120 |
40.00 |
C |
Graph:
A bar chart displays the average
marks of each student.
8. Conclusion
This project helped in
understanding how Python libraries, user-defined functions, and visualization
tools can be used to develop practical applications. The project demonstrates
how data can be processed, analyzed, and presented visually using Python.
9. Future Improvements
The project can be improved by
adding:
- Database
connectivity
- User
login system
- More
subjects
- Automatic
report generation
- Interactive
graphs
✅ Project Type: Python Data
Analysis Project
✅ Libraries
Used: Pandas, Matplotlib
✅ Concepts
Covered: Libraries, Functions, Data Processing, Visualization, Programming
Logic
No comments:
Post a Comment