You are on page 1of 40

Rishabh Jha_CSE4A-G2

Manav Rachna University


Department of Computer Science & Technology
Python Workshop

LAB – 2
# Q1. Check whether a number is even or odd
is_even = int(input("Enter a number: "))
if is_even % 2 == 0:
print("number is even")
else:
print("number is odd")

#Q2. Check whether an entered year is leap year or not.


year = int(input("Enter the year: "))
if (year%4) == 0:
if (year%100) == 0:
if (year%400) == 0:
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
else:
print("{} is a leap year".format(year))
else:
print("{} is not a leap year".format(year))
#Q3. Write a program to check whether a character is vowel or consonants.
is_vowel = input("Enter a character: ")
is_vowel = is_vowel.lower()
if is_vowel == 'a' or is_vowel == 'e' or is_vowel == 'i' or is_vowel == 'o' or is_vowel == 'u':
print("{} is a vowel".format(is_vowel))
else:
print("{} is a consonent".format(is_vowel))

#Q4. Write a program to find the smallest of two numbers.


num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))

#Ternary operator used


min = num1 if num1 < num2 else num2
print("{} is a smallest number".format(min))
#Q5. Find the Factorial of a Number
ret_fac = int(input("Enter the number for factorial: "))
fac = 1
for i in range (1, ret_fac + 1):
fac = fac * i
print("Factorial of number {} is: {}".format(ret_fac, fac))

#Q6. Write a program to print this patterns


# *
# * *
# * * *
#* * * *

def triangle(n):
k = 2*n - 2
for i in range(0, n):
for j in range(0, k):
print(end=" ")

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

n=4
triangle(n)
#Q7. Write a program to print this series: 1 1 2 3 5 8 13
a=0
b=1
print(a, b, end=' ')
for i in range(a, 6):
s=a+b
print(s, end=' ')
a=b
b=s

#Q8. Check whether a number is prime or not


is_prime = int(input("Enter the number: "))
if is_prime > 1:
for i in range(2, is_prime):
if (is_prime % i) == 0:
print("{} is not a prime number".format(is_prime))
break
else:
print("{} is a prime number".format(is_prime))
break
else:
print("{} is not a prime number".format(is_prime))

#Q9. Make a Simple Calculator.


def add(x, y):
return x + y
def sub(x, y):
return x - y
def mul(x, y):
return x * y
def div(x, y):
return x / y
def mod(x, y):
return x % y

val1 = int(input("Enter 1st number: "))


val2 = int(input("Enter 2nd number: "))
print("----Simple calculator----")
print("1.Addition, 2.Subtraction, 3.Multiplication, 4.Division, 5.Remainder")
choice = int(input("Enter choice: "))

if(choice == 1):
print("Sum of {} and {} is: {}".format(val1, val2, add(val1, val2)))
elif(choice == 2):
print("Difference of {} and {} is: {}".format(val1, val2, sub(val1, val2)))
elif(choice == 3):
print("Product of {} and {} is: {}".format(val1, val2, mul(val1, val2)))
elif(choice == 4):
print("Quotient of {} and {} is: {}".format(val1, val2, div(val1, val2)))
elif(choice == 5):
print("Remainder of {} and {} is: {}".format(val1, val2, mod(val1, val2)))

LAB – 3
# Q1. Write a Python program to demonstrate while loop with else statement.
counter = 0
while counter < 3:
print("Inside while loop")
counter += 1
else:
print("Inside else")

# Q2. Write a Python program to print 1st 5 even numbers (use break statement).
num = 1
flag = 0
while num:
if num % 2 == 0:
print(num, end=' ')
flag+=1
elif flag == 5:
break
num += 1

# Q3. Write a Python program to print 1st 4 even numbers (use continue statement).
for i in range(1, 10):
if (i%2 == 0):
if(i < 10):
print(i, end=' ')
else:
continue

# Q4. Write a Python program to demonstrate Pass statements.


for num in [20, 11, 9, 66, 4, 89, 44]:
if num%2 == 0:
pass
else:
print(num, end=' ')

# Q5. Write a Python program to calculate the length of a string.


string = input("Enter string: ")
print("String: {}".format(string))
print("Length of string is: {}".format(len(string)))

# Q6. Write a Python program to count the number of characters (character frequency) in a string
test_str = "thought Though tough"
freq = {}

for i in test_str:
if i in freq:
freq[i] += 1
elif i == " ":
continue
else:
freq[i] = 1
print(freq)
# Q7. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string. If the string
length is less than 2, return instead of the empty string.
test_str1 = "this is test string"
if len(test_str1) < 3:
print(" ")
else:
new = test_str1[:2] + test_str1[-2:]
print(new)

# Q8. Write a Python program to get a string from a given string where all occurrences of its first char have been
changed to '$', except the first char itself
old_string = "cute child cuts cake cleverly"
x = old_string[0]
new_string = old_string.replace(x, "$")
print(new_string.replace("$", x, 1))
# Q9. Write a Python program to get a single string from two given strings, separated by a space and swap the first
two characters of each string.
str1 = input()
str2 = input()
a = str1[0]
b = str2[0]
new_str1 = b + str1[1:]
new_str2 = a + str2[1:]
print("Original string 1: " + str1)
print("Original string 2: " + str2)
print("New string: " + new_str1 + " " + new_str2)

# Q10. Write a Python program to add 'ing' at the end of a given string (length should be at least 3). If the given string
already ends with 'ing' then add 'ly' instead. If the string length of the given string is less than 3, leave it unchanged
def string_update(string):
if len(string) < 3:
return string
elif string.endswith("ing"):
return string.replace("ing", "ly")
string = input()
print("Old string: {} \nNew string: {}".format(string, string_update(string)))

LAB – 4
1. Write a Python program to sum all the items in a list.

sum = 0

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

for element in list1:

sum = sum + element

print("List: {}".format(list1))

print("Sum of items in list: {}".format(sum))

2. Write a Python program to multiplies all the items in a list.

multiply = 1

list2 = [1, 3, 5, 7, 9, 11]

for element in list2:


multiply = multiply * element

print("List: {}".format(list2))

print("Sum of items in list: {}".format(multiply))

3. Write a Python program to get the largest number from a list

list3 = [100, 40, 512, 8, 0, 90, -10]

large = list3[0]

for element in list3:

if large < element:

large = element

print("List: {}".format(list3))

print("Largest in list: {}".format(large))

4. Write a Python program to get the smallest number from a list.

list4 = [100, 40, 512, 8, 0, 90, -10]

small = list4[0]

for element in list4:


if small > element:

small = element

print("List: {}".format(list4))

print("Largest in list: {}".format(small))

5. Write a Python program to count the number of strings where the string length is 2 or more and the first and last
character are same from a given list of strings 
Sample List : ['abc', 'xyz', 'aba', '1221']
Expected Result : 2

def match_words(words):

ctr = 0

for word in words:

if len(word) > 1 and word[0] == word[-1]:

ctr += 1

return ctr

list5 = ['abc', 'xyz', 'aba', '1221']

print(match_words(list5))
6. Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of
non-empty tuples.  
Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]

def last(n):

return n[1]

def list_sort(lists):

return sorted(lists, key=last)

list6 = [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)]

print(list_sort(list6))
7. Write a Python program to remove duplicates from a list.

list7 = [1, 3, 4, 1, 10, 2, 8, 7, 2, 3]

res = []

for x in list7:

if x not in res:

res.append(x)

print("List after removing duplicates: {}".format(res))

8. Write a Python program to check a list is empty or not.

list8 = [1, 2, 3]

if not list8:

print("List is empty")

else:

print("List is filled with elements")

9. Write a Python program to clone or copy a list.

def cloning(old_list):
new_list = []

new_list = old_list

return new_list

l1 = [11,22,33,44,55]

l2 = cloning(l1)

print("Original List: {}".format(l1))

print("New List: {}".format(l2))

10. Write a Python program to find the list of words that are longer than n from a given list of words.

n=4

list_10 = ["abc", "abcre", "qwerty", "xyzwqbc", "bd"]

new_list = []

for x in list_10:

if len(x) > n:

new_list.append(x)

print(new_list)
11. Write a Python function that takes two lists and returns True if they have at least one common member.

def common_member(l1, l2):

a_set = set(l1)

b_set = set(l2)

if (a_set & b_set):

return True

else:

return False

l1 = [2, 4, 6, 8]

l2 = [1, 4, 6, 7]

print(common_member(l1, l2))

12. Write a Python program to print a specified list after removing the 0th, 4th and 5th elements. 
Sample List : ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']
Expected Output : ['Green', 'White', 'Black']
color_list = ['Red', 'Green', 'White', 'Black', 'Pink', 'Yellow']

new_list = []

for index,color in enumerate(color_list):

if index not in (0,4,5):

new_list.append(color)

print("Original List: {}".format(color_list))

print("New List: {}".format(new_list))

LAB – 5
1. Write a Python program to create a tuple.

2. Write a Python program to create a tuple with different data types.

3. Write a Python program to create a tuple with numbers and print one item.
4. Write a Python program to unpack a tuple in several variables.

5. Write a Python program to add an item in a tuple.

6. Write a Python program to convert a tuple to a string.

7. Write a Python program to get the 4th element and 4th element from last of a tuple

8. Write a Python program to find the repeated items of a tuple.


9. Write a Python program to check whether an element exists within a tuple.

10. Write a Python program to convert a list to a tuple.

11. Write a Python program to remove an item from a tuple.

12. Write a Python program to slice a tuple


13. Write a Python program to find the index of an item of a tuple.

14. Write a Python program to find the length of a tuple.

15. Write a Python program to reverse a tuple.

LAB – 6
Dictionary
1. Create an empty dictionary
2. Create the following dictionary
a. Key value
b. A 10
c. B 20

3. Create a dictionary with different datatypes for keys

4. Print all the items of a dictionary


5. Delete an element of a dictionary

6. Delete full dictionary

7. Print a value for a key


8. To check if a key id present in a dictionary

9. Update a value of a key

10. Add a new key value pair


11. Print dictionary for keys{1,10} and values as square of keys

12. Print nested dictionary

13. Concatenate three dictionaries

Sample Dictionary :
dic1={1:10, 2:20}
dic2={3:30, 4:40}
dic3={5:50,6:60}
Expected Result : {1: 10, 2: 20, 3: 30, 4: 40, 5: 50, 6: 60}

14. Sum all the values of a dictionary


15. Accessing an element of a nested dictionary

16. Write a Python script to print a dictionary where the keys are numbers between 1 and 15 (both included) and the
values are square of keys.
Sample Dictionary
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100, 11: 121, 12: 144, 13: 169, 14: 196, 15: 225}
17. Insert factorial of keys in values. And print dictionary

Sets
1. Write a program to create a set

2. Write a program to add an element to set

3. Write a program to add multiple items using update function

4. Write a program to find length of a set

5. Write a program to remove value from a set


6. Write a program to pop an element from a set

7. Write a program to update a set

8. Write a Python program to create an intersection of sets.

9. Write a Python program to create a union of sets.

10. Write a Python program to clear a set.


11. Write a Python program to issubset and issuperset.

12. Write a Python program to create set difference.

13. Write a Python program to create a symmetric difference.

1. Write a program to multiply two numbers using functions.


2. Write a program to add two numbers using functions.

3. Calculate factorial of a number using function.

4. Create sequence of Fibonacci using function.

5. Write a program to swapping of two numbers using functions.


6. Write a function to find the HCF of some given numbers.

7. Write a function to find the ASCII value of the character.

8. Write a program that demonstrates the (built in function) mathematical functions.

9. Write a program that demonstrates the (built in function) Date & Time functions.

10. Write a program that demonstrates Required arguments.


11. Write a program that demonstrates keyword arguments.

12. Write a program that demonstrates Default arguments.

13. Write a program that demonstrates Variable –length arguments.

LAB – 8
1. Write a Python program that create a class tringle and define two methods, create_triangle() and print_sides().
2. Write a Python program to create a class with two methods get_String() and print_String().

3. Write a Python program to create a class Rectangle that takes the parameter length and width. The class should also
contain a method for computing its perimeter.
4. Write a Python program to create a class Circle that takes the parameter radius. The class should also contain two
methods for computing its area & perimeter respectively. Use constructor to implement initialization of parameters

5.Create a Circle class and initialize it with radius. Make two methods getArea and getCircumference inside this
class.

6. Create a Temperature class. Make two methods:


a) convertFahrenheit - It will take Celsius and will print it into Fahrenheit.
b) convertCelsius - It will take Fahrenheit and will convert it into Celsius.
7. Create a Student class and initialize it with name and roll number. Make methods to:
1. Display - It should display all information’s of the student.
2. setAge - It should assign age to student
3. setMarks - It should assign marks to the student.
8. Write a Python class to reverse a string word by word.

LAB – 9
1. Write a Python program that has a class Animal with a method legs(). Create two subclasses Tiger and Dog, access
the method leg explicitly with class Dog and implicitly with the class Tiger.
2. Write a Python program to create a class Employee. Define two subclasses: Engineer and Manager. Every class
should have method named printDesignation() that prints Engineer for Engineer class and Manager for Manager
Class.
3. Write a Python program to demonstrate classes and their attributes.

4. Write a Python program to demonstrate Inheritance and method overriding.


5. Write a Python program to demonstrate multiple Inheritance.

You might also like