Experiment-01
Write and execute scripts based on data types.
Data Type- Python supports 3 categories of data types:
Basic Types: int, float, complex, bool, string, bytes
Container Types: List, Tuple, Set, Dict
User-defined Types: class
Int Data Type: int can be expressed in binary, decimal, octal, and
hexadecimal.
Ex- binary starts with 0b/0B, octal with 0o/0O, hex with 0x/0X
0b10111, 156
# Take int data type
x = 50
#display x:
print(x) # 50
#display the data type of x:
print(type(x)) # <class 'int'>
Float Data Type:
Float can be expressed in fractional or exponential form
Ex- -314.1528, 3.1415e2, 3.141528E2
# Take float data type
y = 10.5
#display y:
print(y) # 10.5
#display the data type of x:
print(type(y)) # <class 'float'>
Complex Data Type:
The complex contains real and imaginary parts.
Ex- 3 + 2j, 1 + 4j
# Take Complex data type
x = 3+2j
#display x:
print(x) # 3+2j
#display the data type of x:
print(type(x)) # <class 'complex'>
Bool Data Type:
bool can take any of the two Boolean values, both starting in caps
Ex. True, False
# Take a bool data type
x = True
y = False
#display x:
print(x)
print(y)
#display the data type of x:
print(type(x)) # <class 'bool'>
print(type(y)) # <class 'bool'>
String Data Type:
String is an immutable collection of Unicode characters enclosed
within
‘’, ‘‘ ’’, ‘“ ’’’
Ex- ‘Ram’, “Shyam”
# Take String data type
x = "Hello World"
#display x:
print(x) # Hello World
#display the data type of x:
print(type(x)) # <class 'str'>
Experiment-02
Write and execute scripts based on collections.
Collection- A Generic term for a container type.
Iterable - means a collection that can be iterated over using a loop.
Ordered Collection- elements are stored in the same order in
which they are inserted.
Unordered Collection- elements are not stored in the same order
in which they are inserted. So, we can not predict at which position
a particular element is present.
Sequence - is the generic term for an ordered collection.
Immutable- means an unchangeable collection.
Mutable- means a changeable collection.
String - ordered collection, immutable, iterable.
List - Ordered Collection, Mutable, iterable
Tuple - Ordered Collection, Immutable, iterable
Set - Unordered Collection, mutable, iterable
Dictionary - Unordered Collection, mutable, iterable.
List - List is a collection which is ordered and changeable.
● Allows duplicate members.
● Lists are used to store multiple items in a single variable.
● Lists are created using square brackets [ ]
● List items are indexed, the first item has index [0], the second
item has index [1] etc.
# Create a list
names = ["Sanjay", " Ravi", "Shivam", "Riya", "Radha"]
print(names)
# Accessing list elements
print(names[1])
# length of list
print(len(names))
Tuple is a collection which is ordered and unchangeable.
● Allows duplicate members.
● Tuples are used to store multiple items in a single variable.
● Tuples are written with round brackets().
# Create empty tuple
a = ()
print(a)
print(type(a))
# tuple with one item
b = (10,)
print(b)
print(type(b))
# tuple with dissimilar item
c = ('Sanjay', 25, 34555.50)
print(c)
print(type(c))
# tuple with similar item
d = (10,20,30, 40, 50)
print(d)
print(type(d))
Set is a collection which is unordered, unchangeable*, and
unindexed.
● No duplicate members allowed.
● Sets are used to store multiple items in a single variable.
● Sets are written with curly brackets {}.
# Create empty set
a = set()
print(a)
print(type(a))
# Set with one item
b={20}
print(b)
# set with similar item
s = {10, 20,30,40,50, 60}
print(s)
Dictionary - Dictionaries are used to store data values in key:value
pairs.
● A dictionary is a collection which is ordered*, changeable and
do not allow duplicates.
● Dictionaries are written with curly brackets{}, and have keys
and values
● Dictionaries are also known as maps or associative arrays.
# Create empty dictionary
d1 = {}
print(d1)
print(type(d1))
# Print the "brand" value of the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])
Experiment-03
Write and execute Python scripts with conditional blocks
Three ways for taking decisions in a program:
Case-I
If condition:
statement1
statement2
## Statements in an if block:
Checking Voter Eligibility:
age = int(input('Enter your age : '))
if age >= 18:
print("You are an adult")
print("You can vote")
print("You have full legal rights")
Case-II
If condition:
statement1
statement 2
else:
statement3
statement 4
## Statements in an if-else block:
Checking even or odd numbers:
number = int(input('enter number : '))
if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
Case-III
If condition:
statement1
elif:
statement2
elif:
statement3
else:
statement4
## Statements in an if-elif-else block:
Temperature Classifier:
temperature = int(input('Enter Outside Temperature : '))
if temperature > 30:
print("It's hot outside!")
elif temperature > 20:
print("It's warm outside")
elif temperature > 10:
print("It's cool outside")
else:
print("It's cold outside!")
Note:
● The colon (:) after if, else, and elif is compulsory.
● Statements in if block, elseblock, and elif block must be
indented.
● Indented statements are treated as a block of statements.
● If-else statements can be nested.
Experiment-04
Write and execute Python scripts with loops
A loop in Python is a programming construct that allows a block of
code to be executed repeatedly until a specific condition is met or for
each item in a sequence.
Python primarily uses two types of loops:
(a) For
(b) while
Uses of for loop
A for loop can be used in two specific situations.
● Repeat a set of statements a finite number of times.
● Iterate through a string, list, tuple, set or dictionary.
● To repeat a set of statements a finite number of times, a built-
in function, range(), is used.
● The range() function generates a sequence of integers
In General:
range(start, stop, step)
Case1:
for var in list:
statement1
statement2
Case2:
for var in list:
statement1
statement2
else:
statement3
statement4
# WAP using pattern to print following pattern
*****
f
*****
*****
*****
*****
n=5
for i in range(5):
print()
for j in range(5):
print("*", end='')
# WAP using while loop whether a number is prime or not
num = int(input("Enter an Integer: "))
i=2
while i <=num-1:
if num %i==0:
print(num,'is not a prime number')
break
i += 1
else:
print(num, 'is a prime number')
Experiment-05
Write and execute Scripts based on Functions and Modules
Function - A Python function is a block of code that performs a
specific and well-defined task.
Two main advantages of a function are:
(a)They help us divide our program into multiple tasks. For each
task, we can define a function. This makes the code modular.
(b) Functions provide a reuse mechanism. The same function can be
called any number of times.
There are two types of Python functions:
● Built-in functions -Ex. len(), sorted(), min(), max() etc
● User-defined functions
Example:
#function definition
def fun():
print(‘My opinions may have changed.‘)
print(‘But not fact that I am right ‘)
# [Link] - A module for mathematical
operations
a = 10
b=5
def add(a, b):
"""Returns the sum of two numbers."""
return a + b
def subtract(a, b):
"""Returns the sum of two numbers."""
return a - b
def multiply(a, b):
"""Returns the sum of two numbers."""
return a * b
def divisible(a, b):
"""Returns the sum of two numbers."""
return a / b
result = add(a, b) # Corrected function call,
passing a and b as arguments
print(result) # Prints the result of the
function call
result1 = subtract(a, b)
print(result1)
result2 = multiply(a, b)
print(result2)
result3 = divisible(a, b)
print(result3)
Python Modules:
A file containing a set of functions you want to include in your
application.
Create a Module
To create a module, just save the code you want in a file with the file
extension .py:
Save this code in a file named [Link]
def greeting(name):
print("Hello, " + name)
Use a Module
using the import statement:
Import the module named mymodule, and call the greeting
function:
import mymodule
[Link]("Ravi Kumar")
Example: Save this code in a file named [Link]
person1 = {
"name": "Ravi Kumar",
"age": 20,
"country": "India"
}
import mymodule
a = mymodule.person1["name"]
print(a)
Experiment-06
Write and execute Scripts based on Packages
Python packages are a way to organise and structure code by
grouping related modules into directories.
● A package is essentially a folder that contains an __init__.py
File and one or more Python files (modules).
● Allows modules to be easily shared and distributed across
Different applications.
Key Components of a Python Package
● Module: A single Python file containing reusable code (e.g.,
[Link]).
● Package: A directory containing modules and a special
__init__.py file.
● Sub-Packages: Packages nested within other packages for deeper
organisation.
Creating and Accessing Packages
1. Create a Directory: create a folder that will act as the package
root.
2. Add Modules: Inside the directory, add Python files (modules).
Each module can contain related functions or classes.
3. Add __init__.py: add an __init__.py file to the directory. This
file tells Python that the directory should be treated as a package.
4. Create Sub-packages (Optional): One can organize code
further by creating subdirectories with their own __init__.py files.
5. Import Modules: Modules or functions inside the package can
be imported using dot notation
math_operations/__init__.py - This file initializes the main
package and exposes commonly used functions so they can be
imported directly from the package.
from .calculate import calculate
from .basic import add, subtract
from .advanced import multiply, divide
math_operations/[Link] - This module contains a simple
function that prints a message indicating that a calculation is being
performed.
def calculate():
print("Performing calculation...")
math_operations/basic/__init__.py - This file initializes the
basic sub-package and makes the add and subtract functions
available when the sub-package is imported.
from .add import add
from .sub import subtract
math_operations/basic/[Link] - This module contains the
function for performing addition.
def add(a, b):
return a + b
math_operations/basic/[Link] - This module contains the function
for performing subtraction.
def subtract(a, b):
return a - b
math_operations/advanced/__init__.py - This file initializes the
advanced sub-package and exposes the multiply and divide functions
from their respective modules.
from .mul import multiply
from .div import divide
math_operations/advanced/[Link] - This module contains the
function for performing multiplication.
def multiply(a, b):
return a * b
math_operations/advanced/[Link] - This module contains the
function for performing division.
def divide(a, b):
return a / b
Using the Package
Now we can import functions from the package and use them in our
program.
from math_operations import calculate, add, subtract, multiply, divide
# Using the placeholder calculate function
calculate()
# Perform basic operations
print("Addition:", add(5, 3))
print("Subtraction:", subtract(10, 4))
# Perform advanced operations
print("Multiplication:", multiply(4, 2))
print("Division:", divide(10, 2))
Output
Performing calculation...
Addition: 8
Subtraction: 6
Multiplication: 8
Division: 5.0
Experiment-07
Write a program which uses exception handling
Python Exception Handling allows a program to gracefully handle
unexpected events (like invalid input or missing files) without
crashing.
n = 10
m=0
try:
ans = n / m
print(ans)
except ZeroDivisionError:
print("Can't be divided by zero!")
Output Can't be divided by zero!
Difference Between Errors and Exceptions
Errors and exceptions are both issues in a program, but they differ in
severity and handling.
● Error: Issues in the program logic, such as SyntaxError, etc. It
occurs at compile time.
● Exception: Problems that occur at runtime and can be managed
using exception handling (e.g., invalid input, missing files).
Example: This example shows the difference between a syntax error
and a runtime exception
# Syntax Error (Error)
print("Hello world" # Missing closing parenthesis
# ZeroDivisionError (Exception)
n = 10
res = n / 0
Syntax of Exception Handling
Python provides four main keywords for handling exceptions: try,
except, else and finally. Each plays a unique role. Let's see syntax:
try:
# Code
except SomeException:
# Code
else:
# Code
finally:
# Code
● try: Runs the risky code that might cause an error.
● except: Catches and handles the error if one occurs.
● else: Executes only if no exception occurs in try.
● Finally, it runs regardless of what happens, which is useful for
cleanup tasks like closing files.
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Output:
You can’t divide by zero!
Execution complete