0% found this document useful (0 votes)
7 views24 pages

Python Class 3 Assignment Solution

The document contains a series of Python programming exercises covering various topics such as conditional statements, loops, string manipulation, list operations, and object-oriented programming. Each exercise includes a problem statement, expected output, and a solution code snippet. The exercises range from finding numbers divisible by certain values to creating classes and functions for specific tasks.

Uploaded by

deypriyanka392
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)
7 views24 pages

Python Class 3 Assignment Solution

The document contains a series of Python programming exercises covering various topics such as conditional statements, loops, string manipulation, list operations, and object-oriented programming. Each exercise includes a problem statement, expected output, and a solution code snippet. The exercises range from finding numbers divisible by certain values to creating classes and functions for specific tasks.

Uploaded by

deypriyanka392
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/ 24

Python Conditional Statements and loops

Q1. Write a Python program to find those numbers which are divisible by 7 and
multiples of 5, between 1500 and 2700 (both included).
Output:
1505,1540,1575,1610,1645,1680,1715,1750,1785,1820,1855,1890,1925,1960,1
995,2030,2065,2100,2135,2170,2205,2240,2275,2310,2345,2380,2415,2450,24

ills
85,2520,2555,2590,2625,2660,2695
Solution:
nl=[]

Sk
for x in range(1500, 2701):
if (x%7==0) and (x%5==0):
nl.append(str(x)) a
print (','.join(nl))
at
Q2. Write a Python program that accepts a word from the user and reverses it.
D

INPUT: Input a word to reverse: Shailja


OUTPUT: ajliahS
w

Solution:
ro

word = input("Input a word to reverse: ")


for char in range(len(word) - 1, -1, -1):
G

print(word[char], end="")
print("\n")

Q3. Write a Python program that prints all the numbers from 0 to 6 except 3 and
6. Note : Use 'continue' statement.
Expected Output : 0 1 2 4 5
Solution:
for x in range(6):
if (x == 3 or x==6):
continue
print(x,end=' ')
print("\n")

ills
Q4. Write a Python program that prints each item and its corresponding type from
the following list.

Sk
INPUT = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V',
"section":'A'}]
OUTPUT: a
Type of 1452 is <class 'int'>
Type of 11.23 is <class 'float'>
at
Type of (1+2j) is <class 'complex'>
D

Type of True is <class 'bool'>


Type of w3resource is <class 'str'>
Type of (0, -1) is <class 'tuple'>
w

Type of [5, 12] is <class 'list'>


ro

Type of {'class': 'V', 'section': 'A'} is < class 'dict'>


G

Solution:
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12],
{"class":'V', "section":'A'}]
for item in datalist:
print ("Type of ",item, " is ", type(item))
Q5. Write a Python program to check the validity of passwords input by users.
Validation :
At least 1 letter between [a-z] and 1 letter between [A-Z].
At least 1 number between [0-9].
At least 1 character from [$#@].
Minimum length 6 characters.

ills
Maximum length 16 characters.

INPUT: Input your password:S3r@100a


OUTPUT:Valid Password

Sk
Solution:

import re
a
p= input("Input your password")
at
x = True
while x:
D

if (len(p)<6 or len(p)>12):
break
w

elif not re.search("[a-z]",p):


break
ro

elif not re.search("[0-9]",p):


break
G

elif not re.search("[A-Z]",p):


break
elif not re.search("[$#@]",p):
break
elif re.search("\s",p):
break
else:
print("Valid Password")
x=False
break

ills
if x:
print("Not a Valid Password")

Sk
Q6. Write a Python program to get the Fibonacci series between 0 and 50.
Note : The Fibonacci Sequence is the series of numbers :
0, 1, 1, 2, 3, 5, 8, 13, 21, ....
a
Every next number is found by adding up the two numbers before it.
Expected Output : 1 1 2 3 5 8 13 21 34
at
D

Solution:
x,y=0,1
while y<50:
w

print(y)
ro

x,y = y,x+y
G

Q7. Write a Python program to check whether an alphabet is a vowel or


consonant.

OUTPUT:

Input a letter of the alphabet: k

k is a consonant.
Solution:

l = input("Input a letter of the alphabet: ")

if l in ('a', 'e', 'i', 'o', 'u'):

print("%s is a vowel." % l)

elif l == 'y':

ills
print("Sometimes letter y stand for vowel, sometimes stand for
consonant.")

else:

Sk
print("%s is a consonant." % l)

a
Q8. Write a Python program that takes a string as input and replaces all
occurrences of a given character with another character.
at
INPUT: Enter a string: We study at GrowDataSkills
D

Enter the character to replace: G

Enter the replacement character: H


w

OUTPUT: Replaced string: We study at HrowDataSkills


ro

Solution:
G

def replace_characters(input_string, old_char, new_char):

replaced_string = ""

for char in input_string:

if char == old_char:
replaced_string += new_char

else:

replaced_string += char

return replaced_string

ills
input_string = input("Enter a string: ")

old_char = input("Enter the character to replace: ")

Sk
new_char = input("Enter the replacement character: ")

print("Replaced string:", replace_characters(input_string, old_char, new_char))

a
Q9: Write a Python function to reverse a list at a specific location(
at
INPUT: [10,20,30,40,50,60,70,80]

start_pos = 2
D

end_pos = 4

OUTPUT: Reverse elements of the said list between index position 2 and 4
w

[10, 20, 50, 40, 30, 60, 70, 80]


ro

Q10. Write a Python program that takes a string as input and checks if it is a
G

palindrome (reads the same forwards and backward).

INPUT: Enter a string: GrowDataSkills

OUTPUT: It is not a palindrome.

Solution:
def is_palindrome(input_string):

return input_string == input_string[::-1]

input_string = input("Enter a string: ")

if is_palindrome(input_string):

print("It is a palindrome.")

ills
else:

print("It is not a palindrome.")

Sk
Q11. Write a Python program that takes a sentence as input and capitalizes the
first letter of each word.
a
INPUT: Enter a sentence: we are growdataskills
at
OUTPUT: Capitalized sentence: We Are Growdataskills

Solution:
D

def capitalize_words(sentence):

words = sentence.split()
w

capitalized_words = [word.capitalize() for word in words]


ro

return " ".join(capitalized_words)


G

input_sentence = input("Enter a sentence: ")

print("Capitalized sentence:", capitalize_words(input_sentence))


Q12. Write a Python program that takes two lists as input and returns a new list
containing the common elements between the two lists.

INPUT:

list1 = [1, 2, 3, 4, 5]

list2 = [3, 4, 5, 6, 7]
OUTPUT: Common elements: [3, 4, 5]

ills
Solution:

def find_common_elements(list1, list2):

Sk
common_elements = [item for item in list1 if item in list2]

return common_elements

list1 = [1, 2, 3, 4, 5]
a
at
list2 = [3, 4, 5, 6, 7]

print("Common elements:", find_common_elements(list1, list2))


D

Python functions
w

Q. Write a Python function to calculate the factorial of a number (a non-negative


ro

integer). The function accepts the number as an argument.

INPUT: Input a number to compute the factorial : 4


G

OUTPUT: 24

Solution:

def factorial(n):

if n == 0:
return 1

else:

return n * factorial(n-1)

n=int(input("Input a number to compute the factorial : "))

print(factorial(n))

ills
Q. Write a Python function that accepts a string and counts the number of upper
and lower case letters.

Sk
INPUT: The quick Brow Fox'

OUTPUT: a
No. of Upper case characters : 3
No. of Lower case Characters : 13
at
Solution:
D

def string_test(s):

d={"UPPER_CASE":0, "LOWER_CASE":0}
w

for c in s:
ro

if c.isupper():

d["UPPER_CASE"]+=1
G

elif c.islower():

d["LOWER_CASE"]+=1

else:

pass
print ("Original String : ", s)

print ("No. of Upper case characters : ", d["UPPER_CASE"])

print ("No. of Lower case Characters : ", d["LOWER_CASE"])

string_test('The quick Brown Fox')

ills
Q. Write a Python function to check whether a number falls within a given
range(3,9)

INPUT:5

Sk
OUTPUT: 5 is in the range

Solution:

def test_range(n):
a
at
if n in range(3,9):

print( " %s is in the range"%str(n))


D

else :

print("The number is outside the given range.")


w

test_range(5)
ro

Q. Write a Python function that takes an integer as input and checks if it is a


G

prime number.

INPUT: Enter an integer: 13

OUTPUT: It is a prime number.

Solution:
def is_prime(n):

if n <= 1:

return False

for i in range(2, int(n ** 0.5) + 1):

if n % i == 0:

ills
return False

return True

Sk
num = int(input("Enter an integer: "))

if is_prime(num):

print("It is a prime number.")


a
else:
at
print("It is not a prime number.")
D

Q. Write a Python function that takes a list of numbers as input and returns the
average of the numbers.
w

INPUT: [1,2,3,4,5,6,7,8,9,10]
ro

OUTPUT: 5.5

Solution:
G

def compute_average(numbers):

if not numbers:

return 0

return sum(numbers) / len(numbers)


input_numbers = [1,2,3,4,5,6,7,8,9,10]

print(compute_average(input_numbers))

Q. Write a Python function that takes a list as input and returns a new list
containing only the unique elements from the input list.

ills
INPUT: [1,2,3,4,1,2,0,0,1]
OUTPUT: [0, 1, 2, 3, 4]
Solution:

Sk
def find_unique_elements(input_list):

return list(set(input_list))
a
at
input_list = [1,2,3,4,1,2,0,0,1]

print("Unique elements:", find_unique_elements(input_list))


D

Q. Write a Python function that takes two strings as input and checks if they are
w

anagrams (contain the same characters in any order).


ro

INPUT:

Enter the first string: race


G

Enter the second string: care

OUTPUT: They are anagrams.

Solution:

def are_anagrams(str1, str2):


return sorted(str1) == sorted(str2)

string1 = input("Enter the first string: ")

string2 = input("Enter the second string: ")

if are_anagrams(string1, string2):

print("They are anagrams.")

ills
else:

print("They are not anagrams.")

Sk
Q. Write a Python function that takes a list and an element as input and returns
the number of occurrences of that element in the list.

INPUT:
a
at
input_list = [ 1,2,3,4,2,2,3,4,5,9,2,6]

Enter the element to count: 2


D

OUTPUT: Occurrences: 4
Solution:
w

def count_occurrences(input_list, element):


ro

return input_list.count(element)
G

input_list = [ 1,2,3,4,2,2,3,4,5,9,2,6]

element_to_count = int(input("Enter the element to count: "))

print("Occurrences:", count_occurrences(input_list, element_to_count))


Q. Write a Python function that takes a list of tuples as input and returns the list
sorted based on the second element of each tuple.

INPUT:[(1, 3), (2, 1), (3, 2), (4, 5), (5, 4)]

OUTPUT: Sorted list of tuples: [(2, 1), (3, 2), (1, 3), (5, 4), (4, 5)]

Solution:

def sort_list_of_tuples_by_second_element(input_list):

ills
return sorted(input_list, key=lambda x: x[1])

Sk
input_list = [(1, 3), (2, 1), (3, 2), (4, 5), (5, 4)]

print("Sorted list of tuples:", sort_list_of_tuples_by_second_element(input_list))


a
at
Q. Write a Python function that takes a list of integers as input and returns the
second largest element in the list.
D

INPUT: [3, 5, 2, 8, 9, 5, 1]

OUTPUT: Second largest element: 8


Solution:
w

def find_second_largest(nums):
ro

nums_set = set(nums)
G

if len(nums_set) < 2:

return None

nums_set.remove(max(nums_set))

return max(nums_set)

input_nums = [3, 5, 2, 8, 9, 5, 1]
print("Second largest element:", find_second_largest(input_nums))

Q.Write a Python lambda function that takes a list of numbers and an exponent
n as input and returns a new list with each element raised to the power of n.

INPUT:

input_numbers = [1, 2, 3, 4, 5]

ills
exponent = 3

OUTPUT: [1, 16, 81, 256, 625]

Sk
Solution:

a=list(map(lambda x: x ** n, input_numbers))
print(a)
a
at
Q. Write a Python function that takes a list of integers as input and returns a new
list containing only the odd numbers.
D

INPUT: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


OUTPUT: [1,3,5,7,9]
Solution:
w

a= list(filter(lambda x: x % 2 != 0, input_numbers))
ro

print(a)
G

Python Object-Oriented Programming

Q. Write a Python program to create a class representing a Circle. Include


methods to calculate its area and perimeter.
INPUT:

Radius of the circle: 4

OUTPUT:

Area of the circle: 50.26548245743669

Perimeter of the circle: 25.132741228718345

ills
Solution:

import math

Sk
class Circle:

def __init__(self, radius):

self.radius = radius a
at
def calculate_circle_area(self):
D

return math.pi * self.radius**2


w

def calculate_circle_perimeter(self):
ro

return 2 * math.pi * self.radius


G

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

circle = Circle(radius)

area = circle.calculate_circle_area()

perimeter = circle.calculate_circle_perimeter()
print("Area of the circle:", area)

print("Perimeter of the circle:", perimeter)

Q. Write a Python program to create a person class. Include attributes like name,
country and date of birth. Implement a method to determine the person's age.

SAMPLE OUTPUT:

ills
Person 1:

Name: Ferdi Odilia

Sk
Country: France

Date of Birth: 1962-07-12

Age: 60
a
at
Person 2:

Name: Shweta Maddox


D

Country: Canada

Date of Birth: 1982-10-20


w

Age: 40
ro

Person 3:

Name: Elizaveta Tilman


G

Country: USA

Date of Birth: 2000-01-01

Age: 23
Solution:

from datetime import date

class Person:

def __init__(self, name, country, date_of_birth):

self.name = name

ills
self.country = country

self.date_of_birth = date_of_birth

Sk
def calculate_age(self):

today = date.today()

age = today.year - self.date_of_birth.year


a
if today < date(today.year, self.date_of_birth.month, self.date_of_birth.day):
at
age -= 1
D

return age
w

# Example usage
ro

person1 = Person("Ferdi Odilia", "France", date(1962, 7, 12))

person2 = Person("Shweta Maddox", "Canada", date(1982, 10, 20))


G

person3 = Person("Elizaveta Tilman", "USA", date(2000, 1, 1))

# Accessing attributes and calculating age

print("Person 1:")

print("Name:", person1.name)
print("Country:", person1.country)

print("Date of Birth:", person1.date_of_birth)

print("Age:", person1.calculate_age())

print("\nPerson 2:")

ills
print("Name:", person2.name)

print("Country:", person2.country)

Sk
print("Date of Birth:", person2.date_of_birth)

print("Age:", person2.calculate_age())

print("\nPerson 3:")
a
at
print("Name:", person3.name)
D

print("Country:", person3.country)

print("Date of Birth:", person3.date_of_birth)


w

print("Age:", person3.calculate_age())
ro

Q. Write a Python program to create a calculator class. Include methods for


basic arithmetic operations.
G

SAMPLE INPUT:7,5

SAMPLE OUTPUT:

7 + 5 = 12

7-5=2
7 * 5 = 35

7/5 = 1.0

Solution:

class Calculator:

def add(self, x, y):

ills
return x + y

def subtract(self, x, y):

Sk
return x - y

def multiply(self, x, y):

return x * y a
def divide(self, x, y):
at
return x / y
D

if __name__ == "__main__":
w

calculator = Calculator()
ro

num1 = 7

num2 = 5
G

print(f"{num1} + {num2} =", calculator.add(num1, num2))

print(f"{num1} - {num2} =", calculator.subtract(num1, num2))

print(f"{num1} * {num2} =", calculator.multiply(num1, num2))

print(f"{num1} / {num2} =", calculator.divide(num1, num2))


Q. Write a Python program to create a class that represents a shape. Include
methods to calculate its area and perimeter. Implement subclasses for different
shapes like circle, triangle, and square.

SAMPLE INPUT:

Circle(5)

ills
Triangle(3, 4, 5)

Square(6)

Sk
SAMPLE OUTPUT:

Circle: a
Area: 78.53981633974483
at
Perimeter: 31.41592653589793
D

Triangle:

Area: 6.0
w

Perimeter: 12
ro

Square:

Area: 36
G

Perimeter: 24

Solution:

import math
class Shape:

def area(self):

pass

def perimeter(self):

pass

ills
class Circle(Shape):

Sk
def __init__(self, radius):

self.radius = radius

def area(self): a
return math.pi * self.radius * self.radius
at
def perimeter(self):
D

return 2 * math.pi * self.radius


w

class Triangle(Shape):
ro

def __init__(self, side1, side2, side3):

self.side1 = side1
G

self.side2 = side2

self.side3 = side3

def area(self):

s = (self.side1 + self.side2 + self.side3) / 2


return math.sqrt(s * (s - self.side1) * (s - self.side2) * (s - self.side3))

def perimeter(self):

return self.side1 + self.side2 + self.side3

class Square(Shape):

ills
def __init__(self, side):

self.side = side

Sk
def area(self):

return self.side * self.side

def perimeter(self): a
return 4 * self.side
at
D

if __name__ == "__main__":

# Create instances of the subclasses


w

circle = Circle(5)
ro

triangle = Triangle(3, 4, 5)

square = Square(6)
G

# Calculate and print the area and perimeter of each shape

print("Circle:")

print("Area:", circle.area())
print("Perimeter:", circle.perimeter())

print("\nTriangle:")

print("Area:", triangle.area())

print("Perimeter:", triangle.perimeter())

ills
print("\nSquare:")

Sk
print("Area:", square.area())

print("Perimeter:", square.perimeter())

a
at
D
w
ro
G

You might also like