0% found this document useful (0 votes)
13 views20 pages

Home Assignment

This document contains a series of Python programming assignments covering various topics such as arithmetic operations, flow control, data structures, functions, and file handling. Each unit includes multiple programs with source code and expected outputs, demonstrating different programming concepts and techniques. The assignments are designed to help learners practice and understand Python programming effectively.

Uploaded by

Sonali Biswas
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)
13 views20 pages

Home Assignment

This document contains a series of Python programming assignments covering various topics such as arithmetic operations, flow control, data structures, functions, and file handling. Each unit includes multiple programs with source code and expected outputs, demonstrating different programming concepts and techniques. The assignments are designed to help learners practice and understand Python programming effectively.

Uploaded by

Sonali Biswas
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

HOME ASSIGNMENT

Python Programming

Unit I – Unit IV

NAME:- RISHIKA BISWAS


UNIT I: Introduction to Python

Program 1.

To write a Python program to perform arithmetic operations on two numbers.


Source Code:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Addition :", a + b)
print("Subtraction :", a - b)
print("Multiplication :", a * b)
print("Division :", a / b)
print("Floor Division :", a // b)
print("Modulus :", a % b)
print("Exponentiation :", a ** b)

Output:

────────────────────────────────────────────────────────────────────────────────

Program 2.

To write a Python program to demonstrate the use of relational and logical


operators.
Source Code:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Relational Operators:")
print("a == b :", a == b)
print("a != b :", a != b)
print("a > b :", a > b)
print("a < b :", a < b)
print("a >= b :", a >= b)
print("a <= b :", a <= b)
print("\nLogical Operators:")
print("a>0 and b>0 :", a > 0 and b > 0)
print("a>0 or b<0 :", a > 0 or b < 0)
print("not(a > b) :", not(a > b))

Output:

────────────────────────────────────────────────────────────────────────────────

Program 3.

To write a Python program to take user input and display formatted output.
Source Code:
name = input("Enter your name: ")
age = int(input("Enter your age: "))
height = float(input("Enter your height in cm: "))

print("\n--- Student Details ---")


print(f"Name : {name}")
print(f"Age : {age} years")
print(f"Height : {height:.2f} cm")

Output:
────────────────────────────────────────────────────────────────────────────────

Program 4.

To write a Python program to perform type conversion between int and float.
Source Code:
a = 10
b = 3.5
print("Original values:", a, b)
print("Type of a:", type(a))
print("Type of b:", type(b))

c = float(a)
d = int(b)
print("\nAfter Type Conversion:")
print("int to float:", c, "->", type(c))
print("float to int:", d, "->", type(d))

e = int(input("Enter a number: "))


f = float(e)
print(f"\nUser input {e} converted to float: {f}")

Output:
────────────────────────────────────────────────────────────────────────────────

Program 5.

To write a Python program to evaluate mathematical expressions using operators.


Source Code:
import math

a = float(input("Enter a number: "))


print("\nMathematical Expressions:")
print(f"Square of {a} : {a**2}")
print(f"Cube of {a} : {a**3}")
print(f"Square root of {a} : {[Link](a):.4f}")
print(f"Floor of {a} : {[Link](a)}")
print(f"Ceil of {a} : {[Link](a)}")
print(f"Absolute of -{a} : {abs(-a)}")
print(f"log10 of {a} : {math.log10(a):.4f}")

Output:
────────────────────────────────────────────────────────────────────────────────

Program 6.

To write a Python program to demonstrate dynamic typing and variable assignment.


Source Code:
x = 10
print(f"x = {x}, type: {type(x)}")

x = 3.14
print(f"x = {x}, type: {type(x)}")

x = "Hello, Python!"
print(f"x = {x}, type: {type(x)}")

x = True
print(f"x = {x}, type: {type(x)}")

x = [1, 2, 3]
print(f"x = {x}, type: {type(x)}")

a, b, c = 5, 10.5, "Python"
print(f"\nMultiple assignment: a={a}, b={b}, c={c}")

Output:
────────────────────────────────────────────────────────────────────────────────

UNIT II: Flow Control and Loops

Program 7.

To write a Python program to check whether a number is even or odd.


Source Code:
num = int(input("Enter a number: "))
if num % 2 == 0:
print(f"{num} is Even")
else:
print(f"{num} is Odd")

Output:

────────────────────────────────────────────────────────────────────────────────

Program 8.
To write a Python program to find the largest among three numbers.
Source Code:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))

if a >= b and a >= c:


largest = a
elif b >= a and b >= c:
largest = b
else:
largest = c

print(f"The largest number is: {largest}")

Output:

────────────────────────────────────────────────────────────────────────────────

Program 9.

To write a Python program to generate Fibonacci series.


Source Code:
n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci Series:")
for i in range(n):
print(a, end=" ")
a, b = b, a + b
print()

Output:
────────────────────────────────────────────────────────────────────────────────

Program 10.

To write a Python program to check whether a number is prime.


Source Code:
num = int(input("Enter a number: "))
if num < 2:
print(f"{num} is not a prime number")
else:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
if is_prime:
print(f"{num} is a Prime Number")
else:
print(f"{num} is not a Prime Number")

Output:

────────────────────────────────────────────────────────────────────────────────

Program 11.

To write a Python program to print patterns using nested loops.


Source Code:
n = int(input("Enter the number of rows: "))

print("\nRight Triangle Pattern:")


for i in range(1, n + 1):
for j in range(1, i + 1):
print("*", end=" ")
print()

print("\nInverted Triangle Pattern:")


for i in range(n, 0, -1):
for j in range(1, i + 1):
print("*", end=" ")
print()

Output:

────────────────────────────────────────────────────────────────────────────────

Program 12.

To write a Python program to demonstrate loop control statements (break, continue,


pass).
Source Code:
print("break — Stop loop when i == 5:")
for i in range(1, 11):
if i == 5:
break
print(i, end=" ")
print()

print("\ncontinue — Skip even numbers:")


for i in range(1, 11):
if i % 2 == 0:
continue
print(i, end=" ")
print()

print("\npass — Placeholder, no action at i == 3:")


for i in range(1, 6):
if i == 3:
pass
else:
print(i, end=" ")
print()

Output:

────────────────────────────────────────────────────────────────────────────────

UNIT III: Data Structures and Functions

Program 13.

To write a Python program to perform string operations (slicing and indexing).


Source Code:
s = input("Enter a string: ")
print(f"\nOriginal String : {s}")
print(f"Length : {len(s)}")
print(f"Uppercase : {[Link]()}")
print(f"Lowercase : {[Link]()}")
print(f"First character : {s[0]}")
print(f"Last character : {s[-1]}")
print(f"Slice [0:5] : {s[0:5]}")
print(f"Reverse : {s[::-1]}")
print(f"Replace o -> 0 : {[Link]('o', '0')}")

Output:

────────────────────────────────────────────────────────────────────────────────

Program 14.

To write a Python program to check whether a string is palindrome.


Source Code:
s = input("Enter a string: ")
cleaned = [Link](" ", "").lower()
if cleaned == cleaned[::-1]:
print(f'"{s}" is a Palindrome')
else:
print(f'"{s}" is not a Palindrome')

Output:
────────────────────────────────────────────────────────────────────────────────

Program 15.

To write a Python program to create and manipulate lists.


Source Code:
my_list = [10, 20, 30, 40, 50]
print("Original List :", my_list)

my_list.append(60)
print("After append(60):", my_list)

my_list.insert(2, 25)
print("After insert(2,25):", my_list)

my_list.remove(40)
print("After remove(40):", my_list)

print("Sorted List :", sorted(my_list))


print("Reversed List :", list(reversed(my_list)))
print("Length:", len(my_list), " | Max:", max(my_list), " | Min:",
min(my_list))
print("Sum :", sum(my_list))

Output:
────────────────────────────────────────────────────────────────────────────────

Program 16.

To write a Python program to remove duplicates from a list.


Source Code:
lst = [1, 2, 3, 2, 4, 3, 5, 1, 6, 5]
print("Original List :", lst)

unique_list = list([Link](lst))
print("Duplicates Removed :", unique_list)

print("\nUsing set() method:")


set_list = sorted(list(set(lst)))
print("Duplicates Removed (set):", set_list)

Output:

────────────────────────────────────────────────────────────────────────────────

Program 17.
To write a Python program to count frequency of elements using dictionary.
Source Code:
lst = [1, 2, 3, 2, 4, 3, 5, 1, 2, 3, 4]
freq = {}
for item in lst:
freq[item] = [Link](item, 0) + 1

print("List:", lst)
print("\nElement Frequency:")
for key, value in sorted([Link]()):
print(f" {key} -> {value} time(s)")

Output:

────────────────────────────────────────────────────────────────────────────────

Program 18.

To write a Python program to define and use user-defined functions.


Source Code:
def greet(name):
return f"Hello, {name}! Welcome to Python."

def add(a, b):


return a + b

def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)

def is_even(num):
return num % 2 == 0
name = input("Enter your name: ")
print(greet(name))

print(f"\nadd(12, 8) = {add(12, 8)}")


print(f"factorial(6) = {factorial(6)}")
print(f"is_even(15) = {is_even(15)}")

Output:

────────────────────────────────────────────────────────────────────────────────

UNIT IV: File Handling

Program 19.

To write a Python program to read data from a file using read().


Source Code:
# Creating [Link] for demonstration
with open("[Link]", "w") as f:
[Link]("Hello, World!\n")
[Link]("Python is powerful.\n")
[Link]("File handling is easy.")

# Reading using read()


with open("[Link]", "r") as f:
content = [Link]()
print("File Contents (using read()):")
print(content)

Output:
────────────────────────────────────────────────────────────────────────────────

Program 20.

To write a Python program to read file line by line using readline().


Source Code:
with open("[Link]", "r") as f:
print("Reading line by line (using readline()):")
line = [Link]()
line_num = 1
while line:
print(f"Line {line_num}: {line}", end="")
line = [Link]()
line_num += 1
print()

Output:

────────────────────────────────────────────────────────────────────────────────

Program 21.

To write a Python program to write data into a file.


Source Code:
filename = "[Link]"
with open(filename, "w") as f:
[Link]("Name: Rahul Sharma\n")
[Link]("Course: BCA\n")
[Link]("Subject: Python Programming\n")
[Link]("Semester: 4th\n")

print(f"Data written to '{filename}' successfully.")

with open(filename, "r") as f:


print("\nVerification - File Contents:")
print([Link]())

Output:

────────────────────────────────────────────────────────────────────────────────

Program 22.

To write a Python program to append data to a file.


Source Code:
filename = "[Link]"
with open(filename, "a") as f:
[Link]("Roll No: 2024BCC042\n")
[Link]("Status: Active\n")

print(f"Data appended to '{filename}' successfully.")

with open(filename, "r") as f:


print("\nUpdated File Contents:")
print([Link]())

Output:
────────────────────────────────────────────────────────────────────────────────

Program 23.

To write a Python program to copy contents from one file to another.


Source Code:
source = "[Link]"
destination = "copy_sample.txt"

with open(source, "r") as src:


content = [Link]()

with open(destination, "w") as dst:


[Link](content)

print(f"File '{source}' copied to '{destination}' successfully.")


print("\nContents of Destination File:")
with open(destination, "r") as f:
print([Link]())

Output:
────────────────────────────────────────────────────────────────────────────────

Program 24.

To write a Python program to count words, lines, and characters in a file.


Source Code:
filename = "[Link]"
with open(filename, "r") as f:
content = [Link]()

lines = [Link]("\n")
words = [Link]()
chars = len(content)
chars_ns= len([Link](" ", "").replace("\n", ""))

print(f"File : {filename}")
print(f"Number of Lines : {len(lines)}")
print(f"Number of Words : {len(words)}")
print(f"Total Characters : {chars}")
print(f"Chars (no spaces): {chars_ns}")

Output:

────────────────────────────────────────────────────────────────────────────────

You might also like