0% found this document useful (0 votes)
2 views

Python

The document outlines various programming exercises in Python, covering basic data types, operators, conditional statements, loops, functions, and classes. It includes example codes for personalized messages, age verification for voting, string manipulation, calculating factorials, sorting lists, calculating the area of a circle, and defining a car class. Each section provides theoretical explanations alongside practical code implementations.

Uploaded by

satvik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python

The document outlines various programming exercises in Python, covering basic data types, operators, conditional statements, loops, functions, and classes. It includes example codes for personalized messages, age verification for voting, string manipulation, calculating factorials, sorting lists, calculating the area of a circle, and defining a car class. Each section provides theoretical explanations alongside practical code implementations.

Uploaded by

satvik
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

PRIYANSHU MISHRA 70125502722 BTECH 3C 1

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: 5, -3, 100

2. Floating Point Numbers (float): Numbers with a decimal point.

o Example: 3.14, -0.5, 2.0

3. Strings (str): A sequence of characters enclosed in single, double, or triple quotes.

o Example: "Hello, World!", 'Python'

4. Booleans (bool): Represents one of two values: True or False.

o Example: True, False

5. Lists (list): Ordered, mutable collection of items.

o Example: [1, 2, 3], ['apple', 'banana', 'cherry']

6. Tuples (tuple): Ordered, immutable collection of items.

o Example: (1, 2, 3), ('a', 'b', 'c')

7. Dictionaries (dict): Unordered collection of key-value pairs.

o Example: {'name': 'Alice', 'age': 25}

8. Sets (set): Unordered collection of unique items.

o Example: {1, 2, 3}, {'apple', 'banana', 'cherry'}

9. None Type (None): Represents the absence of a value or a null value.

o Example: None

Operators in Python:
PRIYANSHU MISHRA 70125502722 BTECH 3C 2

An operator is a symbol or keyword that performs operations on values and


variables. Operators are the foundation of any program and are used to
perform mathematical, logical, and relational operations.

Types of Operators:

1. Arithmetic Operators: Used for basic mathematical operations.

o Example: +, -, *, /, //, %, **

2. Comparison Operators: Used to compare values and return a Boolean (

o Example: ==, !=, >, <, >=, <=

3. Logical Operators: Used to combine conditional statements (

o Example: and, or, not

4. Assignment Operators: Used to assign values to variables (

o Example: =, +=, -=, *=, /=

5. Bitwise Operators: Operate on bits and perform bit-level operations

o Example: &, |, ^, ~, <<, >>

Examples:

//Prompting the user to enter his/her name and age.

name=input(“What’s your name?”)

age=int(input(“What’s your age?”))

//Printing a personalized message

print(“Welcome”, name ,”you are “,age ,”years old”)

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("Name is",name,"age is ",age,"height is",height)

print("is a student",is_student)

print("fruits",fruits)

print("coordinates",coordinates)

print("student details",student)

print("numbers",numbers)

print("what's your favorite color",favorite_color)


PRIYANSHU MISHRA 70125502722 BTECH 3C 4

Output2:

Code 3:

a=10

b=5

sum=a+b

print("the sum is",sum)

diff=a-b

print("the difference is",diff)

mul=a*b

print("product is ",mul)

div=a/b

print("division will be",div)

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

print("is equal to not",is_equal)

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:

Conditional statements in Python allow you to execute different blocks of code


based on
certain conditions. The main types of conditional statements are:
1. If statement
Executes a block of code if a specified condition is True.

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:

Joining two or more strings using +.

greeting = "Hello" + " " + "World!"


print(greeting)
# Output: Hello World!

3. String Repetition:
Repeating a string multiple times.

repeat_str = "Hello! " * 3


print(repeat_str)
# Output: Hello! Hello! Hello!

4. String Indexing and Slicing:


Python strings are indexed ,starting from 0.

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

Methods Description Example


.lower() Converts to lowercase "HELLO".lower() → "hello"

.upper() Converts to "hello".upper() → "HELLO"


uppercase.
.strip() Removes " Hello ".strip() → "Hello"
leading/trailing spaces.
.replace() Replaces substring. "Hello".replace("H", "J") →
"Jello"
.split() Splits string into list. "a,b,c".split(",") → ['a', 'b', 'c']

.join() Joins elements with a "-".join(["a", "b", "c"]) → "a-b-


separator c"
.find() Finds substring index. "hello".find("l") → 2

.count() Counts occurences "banana".count("a") → 3

6. Checking substrings:

text = "Hello, Python!"


print("Python" in text)
# Output: True
print("Java" not in text)
# Output: True

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:

In Python, loops are used to repeatedly execute a block of code as long as a


specified condition is true or for a predefined number of iterations. Python
supports two main types of loops:

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

while count <= 5:


print(count)
count += 1
#Output:
1
2
3
4
5

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.

my_list = [1, 2, 3, "apple", True]

Common list operations:

# 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])

Common array operations:

# Adding elements
my_array.append(5)

# Accessing elements
print(my_array[0]) # 1

# Length of array
print(len(my_array))

Code:

user_input = input("Enter numbers separated by spaces: ")


numbers = [int(num) for num in user_input.split()]
numbers.sort()
print("Sorted numbers in ascending order:", numbers)

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

result = multiply(num1, num2)


print(f"The result of multiplying {num1} and {num2} is {result}")

main()

Code:
import math

def calculate_area(radius):
return math.pi * radius ** 2

radius = float(input("Enter the radius of the circle: "))


area = calculate_area(radius)

print(f"The area of the circle with radius {radius} is: {area:.2f}")

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

A class is a blueprint or template for creating objects (instances). It defines a set of


attributes (properties) and methods (functions) that will be shared by all objects created
from that class.

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:

· make: the manufacturer of the car.

· model: the specific model of the car.

· year: the year the car was manufactured.

· color: the color of the car.

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.

3. Constructor (__init__ Method)


The __init__ method is called automatically when a new object is created from the class.
It's used to initialize the object's attributes with values provided during object creation.
The constructor is a special method in Python that helps set up the object's state.

· 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:

# Defining the Car class


PRIYANSHU MISHRA 70125502722 BTECH 3C 17

class Car:

# Constructor method to initialize the car's attributes

def __init__(self, make, model, year, color):

self.make = make

self.model = model

self.year = year

self.color = color

# Method to display car details

def display_info(self):

print(f"Car Details: {self.year} {self.color} {self.make} {self.model}")

# Creating an object of the Car class

my_car = Car("Lamborghini", "Urus", 2021, "Red")

# Calling the display_info method to print the car details

my_car.display_info()

OUTPUT:

Car Details: 2021 Red Lamborghini Urus


PRIYANSHU MISHRA 70125502722 BTECH 3C 18

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 I/O (Input/Output) Operations

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 'r': Read mode (default), for reading a file.

o 'w': Write mode, for creating or overwriting a file.

o 'a': Append mode, for adding data to the end of an existing file.

o 'rb', 'wb': For binary reading or writing.

· Reading a File: Once a file is open in read mode, the contents can be
accessed using various methods:

o .read(): Reads the entire contents of the file.

o .readline(): Reads a single line at a time.

o .readlines(): Reads all lines and returns them as a list.

· 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:

o .write(): Writes a string to the file.

o .writelines(): Writes a list of strings, each as a separate line.

· Closing a File: After file operations are completed, it is important to close


the file using .close() to ensure all data is saved and resources are freed.

Code:

def convert_text_file(input_file, output_file):


PRIYANSHU MISHRA 70125502722 BTECH 3C 19

# Read data from the input text file

with open(input_file, 'r', encoding='utf-8') as infile:

data = infile.read()

# Convert the data to uppercase (as an example of "formatting")

transformed_data = data.upper()

# Write the transformed data to the output text file

with open(output_file, 'w', encoding='utf-8') as outfile:

outfile.write(transformed_data)

# Example usage:

input_txt = 'input_data.txt' # Replace with your input text file path

output_txt = 'output_data.txt' # Replace with your output text file path

convert_text_file(input_txt, output_txt)

OUTPUT

Input.txt

Hello, this is a test.

This is another line of text.

Let's make it uppercase.

Output.txt

HELLO, THIS IS A TEXT.

THIS IS ANOTHER LINE OF TEXT.

LET'S MAKE IT UPPERCASE.


PRIYANSHU MISHRA 70125502722 BTECH 3C 20

Program-9

Aim: Create a program that uses regular expressions to find all instances of a specific
pattern in a text file.

Theory:

What are regular expressions?

Regular expressions are sequence of characters that define a search pattern.


They are widely used for string searching, pattern matching and text
manipulation.

For example:

• \d+ matches one or more digits


• \w+ matches a word
• [a-zA-Z]+ matches alphabetic words
• \bword\b matches the word “word” with word boundaries.

Python provides the re module to work with regular expressions. Key functions
include:

• re.findall(pattern, text) → Returns a list of all non-overlapping matches of


the pattern.
• re.search(pattern, text) → Returns the first match (if any).
• re.match(pattern, text) → Checks for a match only at the beginning of the
string.

The program:

1. Opens the file and reads its content.


2. Uses re.findall( ) to search for all matches of the given pattern.
3. Prints each match found.

Code:
PRIYANSHU MISHRA 70125502722 BTECH 3C 21

import re

def find_pattern_in_file(file_path, pattern):

try:

with open(file_path, 'r', encoding='utf-8') as file:

content = file.read()

matches = re.findall(pattern, content)

if matches:

print(f"Found {len(matches)} match(es):")

for match in matches:

print(match)

else:

print("No matches found.")

except FileNotFoundError:

print(f"Error: File '{file_path}' not found.")

except Exception as e:

print(f"An error occurred: {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

Suppose sample.txt contains following text.

Hello, you can contact us at [email protected] or [email protected].

For more help, visit our site or reach out to [email protected].

OUTPUT:

Found 3 match(es):

[email protected]

[email protected]

[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:

Exception Handling in Python:

Python provides a way to handle runtime errors using try-except blocks.


Common exceptions include:

- ValueError: Raised when an invalid input type is entered.

- ZeroDivisionError: Raised when attempting to divide by zero.

- TypeError Raised when an operation is applied to an inappropriate type.

Structure of Exception Handling:

1. try block: Contains the code that may raise an exception.

2. except block: Catches and handles specific exceptions.

3. else block: Executes if no exceptions occur.

4. Finally block: Always executes, useful for cleanup tasks.

Code:

# Function to perform division and handle exceptions

def divide_numbers():

try:

# Prompt the user for two numbers

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))


PRIYANSHU MISHRA 70125502722 BTECH 3C 24

# Perform the division

result = num1 / num2

except ZeroDivisionError:

print("Error: Cannot divide by zero.")

except ValueError:

print("Error: Please enter valid numbers.")

else:

print(f"The result of {num1} divided by {num2} is {result}")

# Call the function to execute

divide_numbers()

OUTPUT:

Enter the first number: 10

Enter the second number: 2

The result of 10.0 divided by 2.0 is 5.0

Division by zero:

Enter the first number: 10

Enter the second number: 0

Error: Cannot divide by zero.


PRIYANSHU MISHRA 70125502722 BTECH 3C 25

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.

Basic Components Used in the Calculator:

Component Description

Tk() Creates the main window for the application.

Entry A text box where the user inputs expressions and sees results.

Button Clickable buttons for digits, operations, and actions (like "=" and "Clear").

Frame Used to organize buttons in rows and layout them cleanly.

Geometry manager that arranges widgets in blocks before placing them in the parent
pack()
widget.

How It Works

1. User Interface Setup:


o A window is created with an input field at the top (Entry).
o Buttons for digits and operations are placed in a grid-like layout using
nested Frames.
2. Button Clicks:
o When a user clicks on a digit or operator, it gets appended to the input
field using the click() function.
PRIYANSHU MISHRA 70125502722 BTECH 3C 26

o When "=" is clicked, the calculate() function is called.


3. Expression Evaluation:
o The eval() function evaluates the string expression entered by the user.
o If it’s a valid expression, the result is shown.
o If not, an error is displayed.
4. Clearing Input:
o The "Clear" button clears the input field using the clear() function.

Code:

import tkinter as tk

def click(event):

current = entry.get()

entry.delete(0, tk.END)

entry.insert(0, current + event.widget.cget("text"))

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)

entry = tk.Entry(root, font=("Arial", 24), borderwidth=2, relief="groove", justify="right")

entry.pack(fill="both", ipadx=8, ipady=15, padx=10, pady=10)

button_frame = tk.Frame(root)

button_frame.pack()

buttons = [

['7', '8', '9', '/'],

['4', '5', '6', '*'],

['1', '2', '3', '-'],

['0', '.', '=', '+']

for row in buttons:

row_frame = tk.Frame(button_frame)

row_frame.pack(expand=True, fill="both")

for char in row:


PRIYANSHU MISHRA 70125502722 BTECH 3C 28

if char == "=":

btn = tk.Button(row_frame, text=char, font=("Arial", 18), command=calculate)

else:

btn = tk.Button(row_frame, text=char, font=("Arial", 18))

btn.bind("<Button-1>", click)

btn.pack(side="left", expand=True, fill="both", padx=2, pady=2)

clear_btn = tk.Button(root, text="Clear", font=("Arial", 18), command=clear)

clear_btn.pack(fill="both", padx=10, pady=10)

root.mainloop()

OUTPUT:

A window titled “Simple Calculator” will open.

At the top, there will be a large input box where calculations appear.

Below it, you'll see a 4x4 grid of buttons:

7 8 9 /

4 5 6 *

1 2 3 -

0 . = +
PRIYANSHU MISHRA 70125502722 BTECH 3C 29

You might also like