Sec Assignment2 5
Sec Assignment2 5
Assignment 2:
Problem-1: Write a Python program that accepts a number from the user and checks whether
the number is even or odd.
# Prompt the user to input a number and convert the input to an integer
n = int(input('Enter a number: '))
Problem-2: Write a Python program that accepts three numbers and prints the largest of the
three using conditional statements.
# Prompt the user to enter three numbers and convert them to integers
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
c = int(input('Enter third number: '))
Problem-4: Write a Python program that prints numbers from 1 to 100. For multiples of 3,
print ”Fizz” instead of the number, and for multiples of 5, print ”Buzz”. For numbers that are
multiples of both 3 and 5, print ”FizzBuzz”.
# Loop through numbers from 1 to 100
for i in range(1, 101):
# If none of the above conditions are met, print the number itself
else:
print(i)
Problem-5: Write a Python program to calculate the factorial of a given number using a while
loop.
# Prompt the user to input a number and convert it to an integer
n = int(input('Enter a number: '))
Problem-6: Write a Python program that accepts a number from the user and checks whether
then number is prime or not using a for loop.
# Get an integer input from the user
n = int(input('Enter the number: '))
# If the flag is still 1, it means 'n' was not divisible by any number
other than 1 and itself
if flag == 1:
# Print that the number is prime
print('Is prime')
Problem-7: Write a Python program that prints the following pattern for a given number of
rows:
*
**
***
****
*****
# Loop through numbers from 1 to 5 (both inclusive)
for i in range(1, 6):
# Print '*' repeated 'i' times. The multiplication creates a string
of 'i' asterisks.
print(i * '*')
Problem-8: Write a Python program that counts the number of digits in a given positive integer
using a while loop.
# Prompt the user to input a positive integer and convert it to an integer
n = int(input('Enter a positive integer: '))
# Loop to collect user input, store it in both 'l' and 'l0', and
simultaneously compute the sum
for i in range(n):
l.append(int(input('Enter the integer: '))) # Add to 'l'
l0.append(l[i]) # Keep a copy in 'l0'
sum += l[i] # Increment sum by the current integer
Problem-2: Write a Python program that creates a tuple with 10 numbers. Implement a function
that finds the minimum and maximum values in the tuple without using built-in functions.
import random # Importing the random module to generate random numbers
t = [] # Initializing an empty list to store random integers
# Initialize 'min' to the first element of the list 't' for finding the
minimum value
min = t[0]
# Loop through each element in 't' to find the minimum value
for i in t:
if i < min: # If current element is smaller than 'min', update 'min'
min = i
# Initialize 'max' to the first element of the list 't' for finding the
maximum value
max = t[0]
# Loop through each element in 't' to find the maximum value
for i in t:
if i > max: # If current element is larger than 'max', update 'max'
max = i
Problem-3: Write a Python program to merge two lists into one and remove any duplicates from
the merged list.
l = [1, 2, 3, 4, 4, 2, 1] # First list
l0 = [2, 3, 7, 9, 6, 3, 2, 3] # Second list
# Insert the element 'i' back at its original position, minus 1 (as
elements are shifted after removal)
ml.insert(a - 1, i)
# Get the length of the list and calculate the index of the last element
n = len(ml) - 1
b = ml[n] # Get the last element in the list
ml.remove(b) # Remove the last element
ml.insert(0, b) # Insert the last element at the beginning of the list
Problem-4: Write a Python program that initializes a dictionary with 5 key-value pairs.
Implement functionality to:
• Add a new key-value pair.
• Update the value of an existing key.
• Delete a key-value pair.
Problem-5: Write a Python program using list comprehension that generates a list of squares of
all even numbers between 1 and 20.
# List comprehension to generate even numbers between 1 and 20
l = [i for i in range(1, 21) if i % 2 == 0]
print('List of even numbers between 1 to 20:', l) # Print the list of
even numbers
Problem-6: Write a Python program that accepts a tuple from the user and performs slicing
operations to extract elements based on the start, stop, and step values.
# Prompt the user to enter a string representation of a tuple
t = input('Enter the tuple: ')
Problem-7: Write a Python program that takes a dictionary of student names and marks as input,
and then prints the name of the student with the highest marks.
k=[]
for key in dictionary:
k.append(key)
max=dictionary[k[0]]
for i in k:
if (dictionary[i]>max):
max=dictionary[i]
max_marks=[]
for i in k:
if (dictionary[i]==max):
max_marks.append(i)
print('list of students with maximum marks: ',max_marks)
Problem-8: Write a Python program that converts two lists (one containing keys and the other
containing values) into a dictionary.
# Prompt the user to enter a list of keys separated by commas
key = input('Enter the list of keys (e.g., key1,key2,key3,...): ')
# Split the input strings by commas to create lists of keys and values
keys = key.split(',')
values = value.split(',')
Assignment-4:
Problem-1: Write a Python function that accepts two numbers and returns their sum, difference,
product, and quotient.
# Get the first integer from the user and convert it to an integer
a = int(input('Enter the first number: '))
# Get the second integer from the user and convert it to an integer
b = int(input('Enter the second number: '))
else:
# Print a message if the division is not possible
print('Quotient is not defined')
problem-2: Write a Python function that generates the Fibonacci series up to n terms, where n
is provided by the user.
import numpy as np
Problem-3: Write a recursive Python function that calculates the factorial of a given number.
def factorial(n):
# Base case: if n is 0, return 1 (0! = 1)
if n == 0:
return 1
# Recursive case: multiply n by the factorial of (n-1)
if n > 0:
return n * factorial(n - 1)
# Prompt the user to enter two numbers and convert the input to integers
a = int(input('Enter a number: '))
b = int(input('Enter another number: '))
# Use the 'add' function from the 'mymodule' to add the two numbers
print(mymodule.add(a, b))
# The following lines assume that the module 'mymodule' has additional
functions
# Check if the module contains 'subtract', 'product', and 'divide'
functions
# Use the respective functions to perform subtraction, multiplication,
and division
print(mymodule.subtract(a, b)) # Subtract b from a
print(mymodule.product(a, b)) # Multiply a and b
print(mymodule.divide(a, b)) # Divide a by b (make sure to handle
division by zero)
Problem-5: Write a Python function that checks whether a number is prime or not. Use this
function in a program to check numbers from 1 to 100.
def isprime(n):
# Check if the number is 0
if n < 0:
# negative numbers are not considered prime numbers
return 'please enter non-negative integers...'
# If the flag is still 1, it means 'n' was not divisible by any number
other than 1 and itself
if flag == 1:
# Print that the number is prime
return 'Is prime'
Problem-6: Write a Python function that calculates the area of a rectangle. If only one argument
(the side) is provided, assume it is a square.
def area_of_rectangle(length, width=None):
# If width is not provided, assume it's a square, so width = length
if width is None:
width = length
return area
Problem-7: Write a Python function that accepts three numbers and returns the largest and
smallest of the three.
# Function to find the largest of three numbers
def largest(a, b, c):
n = [a, b, c] # Create a list of the three numbers
max = a # Assume the first number is the largest initially
for i in n:
if i > max: # If the current number is greater than max
max = i # Update max with the current number
return max # Return the largest number
Assignment-5:
Problem-1: Write a Python program that reads the content of a text file and prints it to the
console.
# Prompt the user to enter the name of the file, including the .txt
extension
filename = input('Enter the name of the file (with .txt extension): ')
Problem-3: Write a Python program that reads a text file and counts the number of words in it.
# Prompt the user to enter the filename, including the .txt extension
filename = input('Enter the filename with .txt extension: ')
Problem-4: Write a Python program that copies the content of one file into another file.
# Prompt the user to enter the name of the source file, including the
.txt extension
filename = input('Enter filename with .txt extension: ')
# Prompt the user to enter the name of the destination file, including
the .txt extension
destination_file = input('Enter destination filename with .txt extension:
')
# Open the destination file in read mode ('r') to verify the content
with open(destination_file, 'r') as file:
# Read the entire content of the destination file
c = file.read()
# Print the content to the console
print(c)
Problem-5: Write a Python program that accepts a word from the user and searches for that
word in a text file. The program should display how many times the word appears in the file.
#enter a word to search for
word = input('Enter a word: ')
# Check if the current word matches the input word ignoring the
last character
# This accounts for cases like "word," where a comma is attached
if w[0:len(w)-1] == word:
count += 1
# Print the total count of occurrences
print(count)
Problem-6: Write a Python program that appends new content to an existing file without
overwriting the existing content.
# Get filename and content from the user
filename = input('Enter the name of the file with .txt extension: ')
# Open the file in read mode and display the updated content
with open(filename, 'r') as file:
new_content = file.read()
Problem-7: Write a Python program that reads data from a CSV file and prints the contents to
the console. Each line in the file should be treated as a list of values.
import csv # Importing the CSV module to handle CSV files
Problem-8: Write a Python program that opens a file, reads the contents, and handles
exceptions such as ”file not found” or ”permission denied”.
import csv # Importing the CSV module to handle CSV files
try:
# Open the CSV file in read mode
with open(filename, 'r') as file:
content = csv.reader(file) # Reading the CSV file using
csv.reader which returns an iterable