Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 16

NAME : ZAKRIA

LODHI
DECIPLINE : AI
ROLL NO : 139
TO : DR AAMIR
AKBAR
DATED :
OOP ASSIGNMENT

Question : 01
Create a python program to create the following right-angle triangle
pattern:

*
**
***
****
*****

Right-angle triangle
i = 1

while i <= 5:
print("*"*i, end = '')
i = i + 1
print()
Question : 02
Write a python program to generate the following pattern:
*****
****
***
**
*

Inverted right-angle triangle


num_rows = 5

for i in range(num_rows, 0, -1):

for j in range(1, i + 1):


print("*", end = "")
print()

Question : 03
Create a program to display the following pyramid pattern:
*
**
***
****
*****

Pyramid pattern

num_rows = 5

for i in range(1, num_rows + 1):


for j in range(num_rows, i, -1):
print(" ",end = "")

for k in range(1, i + 1):


print("*", end = "")

print()

Question : 04
Write a python program to produce the following inverted pyramid patter
*****
****
***
**
*

Inverted pyramid pattern


num_rows = 5

for i in range(num_rows, 0, -1):

for j in range(num_rows, i, -1):


print(" ", end = "")

for k in range(1, i + 1):


print("*", end = "")

print()

Question : 05 Half pyramid pattern


*
***
*****
*******
*********

num_rows = 5

for i in range(1, num_rows + 1):

for j in range(num_rows, i, -1):


print(" ", end = "")

for k in range(1, 2 * i):


print("*", end = "")

print()

Question :06 Inverted half pyramid pattern


*********
*******
*****
***
*
rows = 5

for i in range(rows, 0, -1):

for j in range(rows - i):


print(" ", end = "")

for k in range(1, i * 2):


print("*", end = "")

print()

Question : 07 Diamond pattern


*
***
*****
*******
*********
*******
*****
***
*

rows = 5

# upper half of the diamond


for i in range(1, rows + 1):

for j in range(1, rows - i + 1):


print(" ", end = "")

for k in range(1, 2 * i):


print("*", end = "")
print()

# lower half of the diamond


for i in range(rows - 1, 0, -1):

for j in range(1, rows - i + 1):


print(" ", end = "")
for k in range(1, 2 * i):
print("*", end = "")
print()

Question : 08 Hollow rectangle pattern


*******
* *
* *
*******

rows = 4
columns = 7

for i in range(rows):
for j in range(columns):
if i==0 or i==rows-1 or j==0 or j==columns-1:
print("*", end = "")
else:
print(" ", end = "")
print()

Question : 09 Right angle-triangle pattern


*
**
* *
* *
******
rows = 5

for i in range(rows):
for j in range(i+1):
if j==0 or j==i or i==rows-1:
print("*", end = "")
else:
print(" ", end = "")
print()

Question : 10 Zig Zag pattern


* *
* *
* *
* *
*
* *
* *
* *
* *
rows = 9

for i in range(rows):
for j in range(rows):
if i == j or i + j == rows - 1:
print("*", end = "")
else:
print(" ", end = "")

print()

Question : 11
Write a python program that take an integers as input and print ‘even’ if it’s a
even number ‘or’ print ‘odd’ if it’s an odd number:
num = int(input("Enter an integer: "))

if num % 2 == 0:
print("even")
else:
print("odd")

Question : 12
give a list of integers, write a python programe to find sum of all even numbers in
the list:
# sample list of integers
integer_list = [1,2,3,4,5,6,7,8,9,10]

# initialize a variable to store the sum


even_sum = 0

# iterate through the list and add even numbers to the sum
for num in integer_list:
if num % 2 == 0:
even_sum += num

# print the sum of even numbers


print("sum of even numbers:",even_sum)

Question : 13
Create a python program that takes a string as input and prints the last three
characters of the string
# Get user input as a string
input_string = input("Enter a string: ")

# Check if the string has at least three characters


if len(input_string) >= 3:
last_three_characters = input_string[-3:]
print("Last three characters:", last_three_characters)
else:
print("The string is too short to get the last three characters.")

Question : 14
Given a list of integers, use list comprehension to create a new list containing only
the squared values of the even numbers
# Sample list of integers
integer_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use list comprehension to create a new list of squared even numbers


squared_even_numbers = [x ** 2 for x in integer_list if x % 2 == 0]

# Print the new list


print("Squared even numbers:", squared_even_numbers)

Question : 15
Given the list of employee data:
Employee_data = [
(“Alice”, 101, “HR”),
(“Bob”, 102, “Engineering”),
(“Charlie”, 103, “Marketing”),
(“David”, 104, “Finance”)
]
Write a python program that does the following:
1. unpack each tuple in the employee_data list to extract the employee’s name,
employee’s ID, employee’s department
2. for each employee, print a message in the following format: “Employee:
[Employee Name], Employee ID:[Employee ID], Employee department:[Employee
department].”
Your program should use tuple unpacking to achieve this, and it should work for
any list of employee data. Test your program with the provided data.
employees_data = [
("Alice", 101, "HR"),
("Bob", 102, "Engineering"),
("Charlie", 103, "Marketing"),
("David", 104, "Finance")
]

# Iterate through the list and unpack each tuple


for employee in employees_data:
name, employee_id, department = employee
print(f"Employee: {name}, Employee ID: {employee_id}, Department:
{department}")

Question : 16
Create two sets and demonstrate the union, intersection, and different
operations between them
# Create two sets
set1 = {1, 2, 3, 4, 5}
set2 = {3, 4, 5, 6, 7}

# Union of the two sets


union_result = set1.union(set2)
print("Union:", union_result)

# Intersection of the two sets


intersection_result = set1.intersection(set2)
print("Intersection:", intersection_result)

# Difference between the two sets (set1 - set2)


difference_result1 = set1.difference(set2)
print("Difference (set1 - set2):", difference_result1)

# Difference between the two sets (set2 - set1)


difference_result2 = set2.difference(set1)
print("Difference (set2 - set1):", difference_result2)

Question : 17
Write a python program that take a month as input and prints the number of days
in that month. Use a dictionary to map the months to the numbers of days
# Create a dictionary to map months to the number of days
month_days = {
"January": 31,
"February": 28, # Assuming a non-leap year
"March": 31,
"April": 30,
"May": 31,
"June": 30,
"July": 31,
"August": 31,
"September": 30,
"October": 31,
"November": 30,
"December": 31
}

# Get the input month from the user


user_input = input("Enter a month: ")

# Check if the input month is in the dictionary


if user_input in month_days:
days = month_days[user_input]
print(f"{user_input} has {days} days.")
else:
print("Invalid month entered.")

Question : 18
given a list of characters, write a python program to reverse the order of the
characters in the list:
char_list = ['a', 'b', 'c', 'd', 'e']

char_list.reverse()

print(char_list)

Question : 19
Create a list of numbers from 1 to 20 using list comprehension. Only include
numbers that are divisible by both 2 and 3:
divisible_by_2_and_3 = [x for x in range(1, 21) if x % 2 == 0 and x % 3 == 0]
Question : 20
Define a python function that take two integers as input and returns their sum.
Provide an example of calling this function:

def add_numbers(a, b):


return a + b

# example
result = add_numbers(5, 7)
print(result) # This will print 12

Question : 21
Create a python function that calculates the area of a rectangle. It should have
default values for the length and width , with a default rectangle size of 1x1:
def rectangle_area(length=1, width=1):
return length * width

# example of calling function


area = rectangle_area()
print("Default Rectangle Area:", area) # This will print "Default Rectangle
Area: 1"

custom_area = rectangle_area(3, 4)
print("Custom Rectangle Area:", custom_area) # This will print "Custom Rectangle
Area: 12"

Question : 22
Write a python program that reads a text file and count the numbers of lines ,
words and characters in the file. Use function to organize the code:

def count_file_statistics(file_path):
try:
with open(file_path, 'r') as file:
text = file.read()
lines = text.split('\n')
words = text.split()
characters = len(text)

return len(lines), len(words), characters


except FileNotFoundError:
return None # Return None if the file is not found

def main():
file_path = "your_file.txt" # Replace with the path to your text file

result = count_file_statistics(file_path)

if result:
lines, words, characters = result
print(f"Number of lines: {lines}")
print(f"Number of words: {words}")
print(f"Number of characters: {characters}")
else:
print("File not found.")

if __name__ == "__main":
main()

Question : 23
Given a list of words, create a python program that generates a new list
containing only words with three or fewer characters using list comprehension.
def filter_short_words(word_list):
return [word for word in word_list if len(word) <= 3]

words = ["apple", "banana", "cat", "dog", "elephant", "fox", "giraffe"]

short_words = filter_short_words(words)
print("Words with three or fewer characters:", short_words)

Question : 24
Given a string , create a python program that counts the number of vowels(a, e, I,
o, u) in the string using list comprehemsion.
def count_vowels(input_string):
vowels = "AEIOU"
count = len([char for char in input_string.upper() if char in vowels])
return count

input_string = "Hello, World! This is a sample string with vowels."

vowel_count = count_vowels(input_string)
print("Number of vowels:", vowel_count)

Question : 25
Write a python program that takes a dictionary of students and their exam scores
and find the students with the highest score and their name.
def find_student_with_highest_score(scores_dict):
if not scores_dict:
return None

max_score = max(scores_dict.values())
top_students = [student for student, score in scores_dict.items() if score ==
max_score]

if len(top_students) == 1:
return top_students[0], max_score
else:
return top_students, max_score

# Example dictionary of student names and exam scores


student_scores = {
"Alice": 95,
"Bob": 88,
"Charlie": 92,
"David": 95,
"Eve": 89
}

result = find_student_with_highest_score(student_scores)

if result:
students, highest_score = result
if isinstance(students, list):
print("Top students with the highest score of", highest_score, "are:",
", ".join(students))
else:
print("Student with the highest score is", students, "with a score of",
highest_score)
else:
print("No students found.")

Question : 26
You are working on a Python project where you need to utilize several modules to
manage various aspects of your code. You have two modules, MathOperations.py
and StringUtils.py, each containing different functions. In MathOperations.py, you
have the following functions. 1. Add a, b to add two numbers. 2. Subtract a, b to
subtract two numbers. 3. Multiply a, b to multiply two numbers. And
StringUtils.py, you have the following functions. 1. Reverse String s to reverse a
given string. 2. Capitalize String s to capitalize the first letter of each word in a
given string. Your task is to create a Python program that imports and utilizes
these functions from the respective modules. Write a Python program that does
the following. 1. Imports all the functions from MathOperations.py using the from
and the star function. 2. Imports the reverse string function from StringUtils.py
using the from syntax. 3. Call each of the following to perform the following tasks.
1. Add two numbers and print the result. 2. Subtract two numbers and print the
result. 3. Multiply two numbers and print the result. 4. Reverse a given string and
print the reverse string. 5. Capitalize the word in the given string and print the
result. Make sure to demonstrate the usage of the both import and from
statement in your code.
# MythOperations.py

def add(a, b):


return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

# StringUtils.py

def reverse_string(s):
return s[::-1]
def capitalize_words(s):
return s.title()

# Import all functions from MythOperations.py using the "import" statement


import MythOperations

# Import all functions from MythOperations.py using the "from" statement


from MythOperations import *

# Import the reverse_string function from StringUtils.py using the "from"


statement
from StringUtils import reverse_string

# Call the functions to perform various tasks


result_add = MythOperations.add(5, 3)
print("Addition:", result_add)

result_subtract = subtract(8, 4)
print("Subtraction:", result_subtract)

result_multiply = multiply(4, 6)
print("Multiplication:", result_multiply)

input_string = "Hello, World!"


reversed_string = reverse_string(input_string)
print("Reversed String:", reversed_string)

input_string = "python programming is fun"


capitalized_words = StringUtils.capitalize_words(input_string)
print("Capitalized Words:", capitalized_words)

You might also like