0% found this document useful (0 votes)
4 views23 pages

Sec Assignment2 5

The document contains a series of Python programming assignments that cover various topics such as checking even or odd numbers, finding the largest of three numbers, calculating sums and factorials, and manipulating lists and dictionaries. Each problem includes code snippets that demonstrate the required functionality, such as loops, conditionals, and user input handling. The assignments aim to enhance programming skills through practical exercises.

Uploaded by

Neeva Maniya
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)
4 views23 pages

Sec Assignment2 5

The document contains a series of Python programming assignments that cover various topics such as checking even or odd numbers, finding the largest of three numbers, calculating sums and factorials, and manipulating lists and dictionaries. Each problem includes code snippets that demonstrate the required functionality, such as loops, conditionals, and user input handling. The assignments aim to enhance programming skills through practical exercises.

Uploaded by

Neeva Maniya
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/ 23

SEC Assignment

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: '))

# Check if the number is divisible by 2 (even number)


if n % 2 == 0:
# If the remainder is 0, print that the number is even
print('Even number')
else:
# If the remainder is not 0, print that the number is odd
print('Odd 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: '))

# Check if 'a' is greater than or equal to both 'b' and 'c'


if a >= b and a >= c:
# If the condition is true, print that 'a' is the largest number
print(a, 'is the largest')
# Exit the program since we found the largest number
raise SystemExit

# Check if 'b' is greater than or equal to both 'a' and 'c'


if b >= a and b >= c:
# If the condition is true, print that 'b' is the largest number
print(b, 'is the largest')
# Exit the program since we
Problem-3: Write a Python program to calculate the sum of the first n natural numbers using a
for loop.
# Prompt the user to input a natural number and convert it to an
integer
n = int(input('Enter a natural number: '))

# Initialize a variable 'sum' to store the total sum, starting at 0


sum = 0

# Use a 'for' loop to iterate from 1 to n (inclusive)


for i in range(1, n + 1):
# Add the current value of 'i' to 'sum' during each iteration
sum = sum + i

# After the loop finishes, print the final sum


print(sum)

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

# Check if the number is divisible by both 3 and 5 (should be


checked first)
if i % 3 == 0 and i % 5 == 0:
# If true, print 'FizzBuzz'
print('FizzBuzz')

# Check if the number is divisible by 3 only


elif i % 3 == 0:
# If true, print 'Fizz'
print('Fizz')

# Check if the number is divisible by 5 only


elif i % 5 == 0:
# If true, print 'Buzz'
print('Buzz')

# 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: '))

# Check if the input number is negative


if n < 0:
# Print an error message if the number is negative
print('Enter a valid number')

# Check if the input number is zero


elif n == 0:
# Print the factorial of 0, which is 1
print('Factorial is 1')

# Check if the input number is positive


elif n > 0:
# Initialize variables for factorial calculation
i = 1
fact = 1

# Calculate the factorial using a while loop


while i <= n:
# Multiply 'fact' by 'i' to compute the factorial
fact = fact * i
# Increment 'i' by 1 for the next iteration
i += 1

# Print the calculated factorial


print(fact)

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: '))

# Check if the number is 0


if n == 0:
# 0 is not considered a prime number
print('Not a prime')

# Initialize a flag to determine if the number is prime


flag = 1

# Check if the number is not 0 (already handled above)


if n != 0:
# Loop through potential divisors from 2 up to n-1
for i in range(2, n):
# If 'n' is divisible by 'i', it's not a prime number
if n % i == 0:
# Print that the number is not a prime and set flag to 0
print('Not a prime')
flag = 0
# Exit the loop as we found a divisor
break

# 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: '))

# Initialize a variable 'count' to keep track of the number of digits


count = 1

# Continue dividing 'n' by 10 as long as 'n' is greater than 9


while n > 9:
# Divide 'n' by 10 to remove the last digit
n = n / 10

# Increment 'count' by 1 for each division to count the digits


count = count + 1

# Print the total count of digits in the original number


print(count)
Assignment-3:
Problem-1: Write a Python program that accepts a list of integers from the user, and performs
the following operations:
• Sort the list in ascending order.

• Reverse the list.


• Find the sum and average of the list.
n = int(input('Enter the number of integers you wish to add in the list:
'))
l = [] # List to hold the user's input
l0 = [] # Copy of the original list for reversing later
sum = 0 # Variable to store the sum of all numbers

# 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

print('List of integers you entered: ', l)

# Sorting the list manually by repeatedly finding the smallest element.


# This is similar to the selection sort algorithm.
x = []
for i in range(len(l)):
min = l[0] # Start by assuming the first element is the smallest
# Traverse the list to find the actual minimum element
for j in range(len(l)):
if l[j] < min:
min = l[j]
x.append(min) # Append the found minimum to the new list
l.remove(min) # Remove the minimum from the original list to avoid
duplicating it in the next iteration

print('List sorted in ascending order: ', x)


# Reverse the original list using its copy, which hasn't been modified
during sorting
l0.reverse()

print('Reverse of list: ', l0)

# Output the sum and calculate the average


print('Sum of all elements of the list: ', sum)
print('Average: ', sum / n)

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

# Loop to generate 10 random integers between 1 and 10 and append them


to the list 't'
for i in range(10):
t.append(random.randint(1, 10))

# Convert the list 't' to a tuple and print it


print(tuple(t))

# 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

# Print the minimum and maximum values


print('minimum value: ', min)
print('maximum value: ', max)

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

# Merge the two lists into one


ml = l + l0
print(ml) # Print the merged list

# Loop through each element in the merged list 'ml'


for i in ml:
a = ml.index(i) # Find the index of the first occurrence of element
'i'

# Inner loop to remove all occurrences of the current element 'i'


for j in ml:
if i == j: # If element 'i' is the same as 'j' (another occurrence
of the same element)
ml.remove(j) # Remove the element 'j' from the list 'ml'

# 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

# Print the final modified list


print(ml)

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.

# Initializing the dictionary with key-value pairs


d = {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
print('Initial dictionary:', d) # Print the initial dictionary

# Adding a new key-value pair (key 6 with value 'f')


d[6] = 'f'
print('Added dict:', d) # Print the dictionary after adding a new pair

# Updating the value of an existing key (key 4) to 'q'


d[4] = 'q'
print('Updated dict:', d) # Print the dictionary after updating the
value

# Deleting the key-value pair where the key is 3


del d[3]
print('After deleting a key-value pair, we get:', d) # Print the
dictionary after deletion

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

# List comprehension to generate squares of the even numbers in 'l'


squares = [x**2 for x in l]
print('List of squares:', squares) # Print the list of squares of the
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: ')

# Create a list using list comprehension


# Extract every 3rd element starting from index 1 of the input string
# Convert each selected character to an integer
list = [int(t[i]) for i in range(1, len(t), 3)]

# Convert the list to a tuple


tuple = tuple(list)

# Print the resulting tuple


print(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.

input_str=input('enter the dictionary of student names and marks as input


(e.g., key1:value1,key2:value2): ')
pairs=input_str.split(',')
dictionary={}
for pair in pairs:
key, value= pair.split(':')
dictionary[key] = value

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,...): ')

# Prompt the user to enter a list of values separated by commas


value = input('Enter the list of values (e.g., value1,value2,value3,...):
')

# Split the input strings by commas to create lists of keys and values
keys = key.split(',')
values = value.split(',')

# Initialize an empty dictionary


d = {}

# Loop through the range of the number of keys (and values)


for i in range(len(keys)):
# Assign each key to its corresponding value in the dictionary
d[keys[i]] = values[i]
# Print the resulting dictionary
print(d)

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: '))

# Calculate and print the sum of the two numbers


print('Sum is', a + b)

# Calculate and print the difference between the two numbers


print('Difference is', a - b)

# Calculate and print the product of the two numbers


print('Product is', a * b)

# Check if the second number is not zero to avoid division by zero


if b != 0:
# Calculate and print the quotient of the two numbers
print('Quotient is', a / b)

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

# Get the number of terms to generate in the Fibonacci sequence


n = int(input('Enter number of terms: '))

# Initialize a numpy array 'f' with zeros of size 'n'


f = np.zeros(n)

# The first two terms of the Fibonacci sequence


f[0] = 0
f[1] = 1

# Generate the Fibonacci sequence up to 'n' terms


for i in range(2, n):
# Each term is the sum of the two preceding terms
f[i] = f[i-1] + f[i-2]

# Print the Fibonacci sequence as a comma-separated string


# Convert each term to an integer and then to a string for joining
print(", ".join(str(int(f[i])) for i in range(n)))

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 a number


n = int(input('Enter the number whose factorial you wish to calculate:
'))

# Calculate and print the factorial of the number


print(factorial(n))
Problem-4: Write a Python module that contains functions for addition, subtraction,
multiplication, and division. Import this module into your main program and perform operations
on two numbers provided by the user.
# Import the custom module named 'mymodule'
import mymodule

# 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...'

# Check if the number is 0


if n == 0:
# 0 is not considered a prime number
return 'Not a prime'
# Check if the number is 1
if n == 1:
# 1 is not considered a prime number
return 'Not a prime'

# Initialize a flag to determine if the number is prime


flag = 1

# Check if the number is not 0 (already handled above)


if n > 1:
# Loop through potential divisors from 2 up to n-1
for i in range(2, n):
# If 'n' is divisible by 'i', it's not a prime number
if n % i == 0:
# Print that the number is not a prime and set flag to 0
return 'Not a prime'
flag = 0
# Exit the loop as we found a divisor
break

# 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'

prime = [] # List to store prime numbers


not_prime = [] # List to store non-prime (composite) numbers

# Loop through numbers from 1 to 100


for i in range(1, 101):
# Check if the number is prime
if (isprime(i) == 'Is prime'):
prime.append(i) # Add the prime number to the prime list
# Check if the number is not prime (composite)
if (isprime(i) == 'Not a prime'):
not_prime.append(i) # Add the non-prime number to the not_prime
list

# Print the list of prime numbers from 1 to 100


print('List of prime numbers from 1 to 100:', prime)
# Print the list of non-prime (composite) numbers from 1 to 100
print('List of composite numbers from 1 to 100:', not_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

# Calculate the area of the rectangle (or square)


area = length * width

return area

# User input for length


length = float(input('Enter the length (in cm): '))

# User input for width


width_input = input('Enter the width (in cm) (write "none" if you don\'t
wish to enter a value): ')

# Check if the user entered "none" for width


if width_input.lower() == 'none':
width = None
else:
width = float(width_input)
# Calculate and print the area
print(f' Area is {area_of_rectangle(length, width): .2f} sq.cm')

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

# Function to find the smallest of three numbers


def smallest(a, b, c):
n = [a, b, c] # Create a list of the three numbers
min = a # Assume the first number is the smallest initially
for i in n:
if i < min: # If the current number is smaller than min
min = i # Update min with the current number
return min # Return the smallest number

# Get user input for the three numbers


a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
c = int(input('Enter third number: '))

# Print the largest and smallest numbers


print('Largest number is', largest(a, b, c))
print('Smallest number is', smallest(a, b, c))
Problem-8: Write a Python program that uses the math module to calculate and print the value
of e^x, sin(x), and log(x) for a user-defined x.
import math # Importing the math module to use mathematical functions

# Taking user input and converting it to a float (decimal) value


x = float(input('Enter x: '))

# Printing the exponential of x (e^x)


print(math.exp(x))

# Printing the sine of x (sin(x)), where x is in radians


print(math.sin(x))

# Printing the natural logarithm of x (log base e, also known as ln(x))


print(math.log(x)) # Note: x must be positive for log(x) to be valid

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): ')

# Open the file in read mode ('r')


# The 'with' statement ensures that the file is properly closed after its
block is executed
with open(filename, 'r') as file:
# Read the entire content of the file into the 'content' variable
content = file.read()

# Print the content of the file to the console


print(content)
Problem-2: Write a Python program that accepts a string from the user and writes it to a text
file.
# Prompt the user to enter the filename, including the .txt extension
filename = input('Enter filename with .txt extension: ')

# Open the file in write mode ('w')


# If the file does not exist, it will be created. If it exists, it will
be truncated
with open(filename, 'w') as file:
# Write a string to the file
file.write('Hello I am Neeva')

# Open the file in read mode ('r')


with open(filename, 'r') as file:
# Read the content of the file
content = file.read()
# Print the content of the file to the console
print(content)

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: ')

# Open the file in read mode ('r')


with open(filename, 'r') as file:
# Read the entire content of the file
content = file.read()

# Remove leading and trailing whitespace from the content


content = content.strip()

# Split the content into words based on whitespace


words = content.split()

# Print the number of words


print(len(words))

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 source file in read mode ('r')


# The 'with' statement ensures that the file is properly closed after its
block is executed
with open(filename, 'r') as file:
# Read the entire content of the source file
content = file.read()

# Open the destination file in write mode ('w')


# If the destination file does not exist, it will be created. If it
exists, it will be truncated
with open(destination_file, 'w') as file:
# Write the content read from the source file into the destination
file
file.write(content)

# 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: ')

#enter the filename to search in


filename = input('Enter the filename where you want to search for the
above word (with .txt extension): ')

# Open the specified file in read mode


with open(filename, 'r') as file:
# Read the entire content of the file
content = file.read()

# Strip leading and trailing whitespace from the content


text = content.strip()

# Split the content into a list of words


words = text.split()

# Initialize a count variable to keep track of occurrences


count = 0

# Iterate through each word in the list


for w in words:
# Check if the current word matches the input word exactly
if w == word:
count += 1

# 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: ')

# Check if the filename ends with '.txt'


if not filename.endswith('.txt'):
print("Error: The filename must end with '.txt'")
else:
content = input('Enter the content you wish to add: ')

# Open the file in append mode and write the content


with open(filename, 'a') as file:
file.write(content + '\n') # Adding a newline after the content
for readability

# Open the file in read mode and display the updated content
with open(filename, 'r') as file:
new_content = file.read()

# Print the updated content


print("\nUpdated File Content:")
print(new_content)

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

# Taking the file name as input from the user


filename = input('Enter the name of the CSV file: ')

# 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

# Iterating through each row in the CSV file


for row in content:
print(row) # Printing each row (which is a list of values from
that row)

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

# Taking the file name as input from the user


filename = input('Enter the name of the CSV file: ')

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

# Iterating through each row in the CSV file


for row in content:
print(row) # Printing each row (which is a list of values
from that row)

# Handling the case where the file is not found


except FileNotFoundError:
print(f"Error: The file '{filename}' was not found. Please try
again.") # Informing the user that the file doesn't exist

# Handling any other unexpected errors


except Exception as e:
print(f"An error occurred: {e}") # Catching any other general
exceptions and printing the error message

You might also like