Python
Python
Program-1
Aim: Basic data types and operators. Create a program that use for their name
and age and prints a personalized message.
Theory:
Data Types in Python: In Python, data types represent the kind of data a variable can hold.
The type of a variable determines what operations can be performed on it and how much
space it occupies in memory. The basic data types in Python are:
1. Integers (int): Whole numbers, positive or negative.
o Example: None
Operators in Python:
PRIYANSHU MISHRA 70125502722 BTECH 3C 2
Types of Operators:
o Example: +, -, *, /, //, %, **
Examples:
Output1:
PRIYANSHU MISHRA 70125502722 BTECH 3C 3
Code 2:
age=35
height=3.4
name="priyanshu"
is_student=True
fruits=["apple","guava","cherry"]
coordinates = (45,55)
student={"name":"Priyanshu","age":21}
numbers={6,7,8,9,10}
favorite_color=None
print("is a student",is_student)
print("fruits",fruits)
print("coordinates",coordinates)
print("student details",student)
print("numbers",numbers)
Output2:
Code 3:
a=10
b=5
sum=a+b
diff=a-b
mul=a*b
print("product is ",mul)
div=a/b
floor =a//b
print("floor division",floor)
mod=a%b
print("modulus result",mod)
expo=a**b
print("exponentiation",expo)
is_equal=a==b
PRIYANSHU MISHRA 70125502722 BTECH 3C 5
is_greater=a>b
print("is greater",is_greater)
x=True
y=False
and_result= x and y
or_result=x or y
not_result=not x
print("AND",and_result)
print("OR",or_result)
print("NOT",not_result)
c=5
c+=3
print(c)
d=10
d*=2
print(d)
Output3:
PRIYANSHU MISHRA 70125502722 BTECH 3C 6
Program-2
Aim: Conditional statements: Create a program that prompts the user for their
age and tells them if they can vote in the next election.
Theory:
x = 10
if x > 5:
print("x is greater than 5")
2. If-else statement
Provides an alternative block of code to execute if the condition is false.
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
3. If-elif-else statement
Allows checking multiple conditions sequentially.
x = 10
if x > 10:
print("x is greater than 10")
elif x == 10:
print("x is equal to 10")
else:
print("x is less than 10")
4. Nested if statements
An if statement inside another if.
PRIYANSHU MISHRA 70125502722 BTECH 3C 7
x = 15
if x > 10:
print("x is greater than 10")
if x % 2 == 0:
print("x is even")
else:
print("x is odd")
Code:
age=int(input("Enter your age"))
if(age>18):
print("Eligible to vote")
else:
print("Not eligible to vote")
Output:
PRIYANSHU MISHRA 70125502722 BTECH 3C 8
Program-3
Aim: String and string manipulation: Create a program that prompts the user for a
string and then prints the string reversed.
Theory:
Strings in Python are sequences of characters enclosed in
single(‘),double(“),triple(‘’’)quotes.
1. Definition:
str1 = 'Hello'
str2 = "World"
str3 = '''This is a multiline string'''
2. String Concatenation:
3. String Repetition:
Repeating a string multiple times.
s = "Python"
print(s[0])
# Output: P (First character)
print(s[-1])
# Output: n (Last character)
print(s[1:4])
# Output: yth (Substring from index 1 to 3)
5. String Methods:
Python provides many built-in string methods.
PRIYANSHU MISHRA 70125502722 BTECH 3C 9
6. Checking substrings:
Code:
str = "Priyanshu"
reverse = "".join(reversed(str))
print("Original string",str)
print("Reversed string",reverse)
Output:
PRIYANSHU MISHRA 70125502722 BTECH 3C 10
Program-4
Aim: Loops: Create a program that calculates the factorial of a number entered by
the user using a loop.
Theory:
1. For loop:
Used to iterate over a sequence (like a list, tuple, string, or
range).
• Executes the block of code for each element in the sequence.
For example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
#Output:
apple
banana
cherry
2. While loop:
Repeats as long as the condition is true.
• Be careful of infinite loops if the condition never becomes False.
For example:
count = 1
PRIYANSHU MISHRA 70125502722 BTECH 3C 11
Code:
def factorial_for(n):
factorial = 1
for i in range(1, n + 1):
factorial *= i
return factorial
# Example
num = 5
print(f"Factorial of {num} using for loop: {factorial_for(num)}")
Output:
PRIYANSHU MISHRA 70125502722 BTECH 3C 12
Program-5
Aim: Lists and arrays: Create a program that prompts the user for a list of
numbers and then sorts them in ascending order.
Theory:
1. Lists:
A list is a built-in Python data structure that can store a collection
of items, which can be of different data types (e.g., integers, strings,
objects).
• Lists are created by enclosing items in square brackets
[],separated by commas.
# Accessing elements
print(my_list[0]) # 1
# Adding elements
my_list.append(4)
# Removing elements
my_list.remove("apple")
# Slicing
sublist = my_list[1:3]
# Length of list
print(len(my_list))
2. Arrays:
The array module in Python provides a way to store data in an
array-like structure. Unlike lists, arrays are more efficient for
numerical operations and store elements of the same data type.
• Arrays are created using the array module, specifying the type
code for the data type.
PRIYANSHU MISHRA 70125502722 BTECH 3C 13
import arrays
my_array =array.array(‘I’,[1,2,3,4])
# Adding elements
my_array.append(5)
# Accessing elements
print(my_array[0]) # 1
# Length of array
print(len(my_array))
Code:
Output:
PRIYANSHU MISHRA 70125502722 BTECH 3C 14
Program-6
Aim: Functions: Create a program that defines a function to calculate the area of
circle based on the radius entered by the user.
Theory:
Functions:
Functions in Python are blocks of reusable code that perform a specific
task. Functions help to organizes and structure the code better. They allow
for modularity, reusability, and a cleaner, more understandable codebase.
Defining a function:
A function is defined using def keyword, followed by the function name,
parentheses, and a colon. The code inside the function is indented.
def function_name(parameters):
# function body
return value
Function scope:
Local variables: Defined using a function and can only be accessed within
that function.
Global variables: Defined outside of any function and can be accessed
from anywhere in the code.
Example:
def multiply(a, b):
return a * b
def main():
num1 = 4
num2 = 5
PRIYANSHU MISHRA 70125502722 BTECH 3C 15
main()
Code:
import math
def calculate_area(radius):
return math.pi * radius ** 2
Output:
PRIYANSHU MISHRA 70125502722 BTECH 3C 16
Program-7
Aim: Create a program that defines a class to represent a car and then creates an object
of that class with specific attributes in python.
Theory:
1. Class Definition
In the example, the Car class is a template that describes a car's properties (make,
model, year, color) and behaviors (like displaying car information).
2. Attributes (Properties)
Attributes are characteristics or properties that an object can have. In the Car class, the
attributes are:
These attributes are initialized using the __init__ method (known as the constructor).
The self keyword refers to the current instance of the class, and the attributes are
assigned using self.attribute_name.
· The __init__ method takes self (the instance of the object) and other
parameters (make, model, year, color) as arguments.
· Inside the __init__ method, the attributes of the object (self.make, self.model, etc.)
are set to the passed values.
Code:
class Car:
self.make = make
self.model = model
self.year = year
self.color = color
def display_info(self):
my_car.display_info()
OUTPUT:
Program-8
Aim: Create a program that reads data from a file and writes it to another file in a
different format in python.
Theory:
File handling in programming refers to the process of reading from and writing to files. In
Python, this is done using built-in functions and methods that interact with the file
system.
· Opening a File: Files must be opened before they can be read or written to.
The open() function in Python allows you to specify the mode in which the file
should be opened, such as:
o 'a': Append mode, for adding data to the end of an existing file.
· Reading a File: Once a file is open in read mode, the contents can be
accessed using various methods:
· Writing to a File: Writing to a file involves opening the file in write mode ('w'
or 'a'). Once open, the file can be modified or written to using:
Code:
data = infile.read()
transformed_data = data.upper()
outfile.write(transformed_data)
# Example usage:
convert_text_file(input_txt, output_txt)
OUTPUT
Input.txt
Output.txt
Program-9
Aim: Create a program that uses regular expressions to find all instances of a specific
pattern in a text file.
Theory:
For example:
Python provides the re module to work with regular expressions. Key functions
include:
The program:
Code:
PRIYANSHU MISHRA 70125502722 BTECH 3C 21
import re
try:
content = file.read()
if matches:
print(match)
else:
except FileNotFoundError:
except Exception as e:
file_path = 'sample.txt'
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
find_pattern_in_file(file_path, pattern)
PRIYANSHU MISHRA 70125502722 BTECH 3C 22
OUTPUT:
Found 3 match(es):
[email protected]
PRIYANSHU MISHRA 70125502722 BTECH 3C 23
PROGRAM-10
Aim: Create a program that prompts the user for two numbers and divides them, handles
any exceptions that may arise in python.
Theory:
Code:
def divide_numbers():
try:
except ZeroDivisionError:
except ValueError:
else:
divide_numbers()
OUTPUT:
Division by zero:
PROGRAM-11
Aim: Create a program that uses a graphical user interface (GUI) to allow the user to
simple calculations.
Theory:
What is Tkinter?
Tkinter is Python’s standard library for building graphical user interfaces (GUIs). It
provides tools to create windows, buttons, input fields, labels, and more.
With Tkinter, you can build cross-platform desktop apps without installing any extra
packages, because it comes built-in with Python.
Component Description
Entry A text box where the user inputs expressions and sees results.
Button Clickable buttons for digits, operations, and actions (like "=" and "Clear").
Geometry manager that arranges widgets in blocks before placing them in the parent
pack()
widget.
How It Works
Code:
import tkinter as tk
def click(event):
current = entry.get()
entry.delete(0, tk.END)
def clear():
entry.delete(0, tk.END)
def calculate():
try:
result = eval(entry.get())
entry.delete(0, tk.END)
entry.insert(0, str(result))
except Exception:
entry.delete(0, tk.END)
PRIYANSHU MISHRA 70125502722 BTECH 3C 27
entry.insert(0, "Error")
root = tk.Tk()
root.title("Simple Calculator")
root.geometry("300x400")
root.resizable(False, False)
button_frame = tk.Frame(root)
button_frame.pack()
buttons = [
row_frame = tk.Frame(button_frame)
row_frame.pack(expand=True, fill="both")
if char == "=":
else:
btn.bind("<Button-1>", click)
root.mainloop()
OUTPUT:
At the top, there will be a large input box where calculations appear.
7 8 9 /
4 5 6 *
1 2 3 -
0 . = +
PRIYANSHU MISHRA 70125502722 BTECH 3C 29