Assignment 1: Introduction to Basic Python
Practice Set:
1. A cashier has currency notes of denomination 1, 5 and 10. Write python script to accept the
amount to be withdrawn from the user and print the total number of currency notes of each
denomination the cashier will have to give.
Program:
amount = int(input("Enter the amount to be withdrawn: "))
tens = amount // 10
amount %= 10
fives = amount // 5
amount %= 5
ones = amount
print("Currency notes needed:")
print("10s =", tens)
print("5s =", fives)
print("1s =", ones)
Output:
2. Write a python script to accepts annual basic salary of an employee and calculates and
displays the Income tax as per the following rules.
Basic: < 2,50,000 Tax = 0
Basic: 2,50,000 to 5,00,000 Tax = 10%
Basic: > 5,00,000 Tax = 20
Program:
basic_salary = float(input("Enter annual basic salary: "))
if basic_salary < 250000:
tax = 0
elif basic_salary <= 500000:
tax = 0.10 * basic_salary
else:
tax = 0.20 * basic_salary
print("Income Tax to be paid: ₹", tax)
Output:
3. Write python script to accept the x and y coordinate of a point and find the quadrant in
which the point lies.
Program:
x = float(input("Enter x coordinate: "))
y = float(input("Enter y coordinate: "))
if x > 0 and y > 0:
print("The point lies in Quadrant I")
elif x < 0 and y > 0:
print("The point lies in Quadrant II")
elif x < 0 and y < 0:
print("The point lies in Quadrant III")
elif x > 0 and y < 0:
print("The point lies in Quadrant IV")
elif x == 0 and y != 0:
print("The point lies on Y-axis")
elif y == 0 and x != 0:
print("The point lies on X-axis")
else:
print("The point is at the Origin")
Output:
4. Write a python script to accept the cost price and selling price from the keyboard. Find out
if the seller has made a profit or loss and display how much profit or loss has been made.
Program:
selling_price = float(input("Enter selling price: "))
if selling_price > cost_price:
profit = selling_price - cost_price
print("Profit made: ₹", profit)
elif cost_price > selling_price:
loss = cost_price - selling_price
print("Loss incurred: ₹", loss)
else:
print("No profit, no loss.")
Output:
Set A:
1. Write python script to calculate sum of digits of a given input number.
Program:
num = int(input("Enter a number: "))
sum_digits = 0
while num > 0:
sum_digits += num % 10
num //= 10
print("Sum of digits =", sum_digits)
Output:
2. Write python script to check whether a input number is Armstrong number or not.
Program:
num = int(input("Enter a number: "))
digits = len(str(num))
temp = num
sum_pow = 0
while temp > 0:
digit = temp % 10
sum_pow += digit ** digits
temp //= 10
if sum_pow == num:
print("Armstrong number")
else:
print("Not an Armstrong number")
Output:
3. Write python script to check whether a input number is perfect number of not.
Program:
num = int(input("Enter a number: "))
sum_div = 0
for i in range(1, num):
if num % i == 0:
sum_div += i
if sum_div == num:
print("Perfect number")
else:
print("Not a perfect number")
Output:
4. Write a program to calculate XY
Program:
x = int(input("Enter X: "))
y = int(input("Enter Y: "))
print("X^Y =", x ** y)
Output:
5. Write a program to check whether a input number is palindrome or not.
Program:
num = input("Enter a number: ")
if num == num[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Output:
6. Write a program to calculate sum of first and last digit of a number.
Program:
num = input("Enter a number: ")
first = int(num[0])
last = int(num[-1])
print("Sum of first and last digit =", first + last)
Output:
Set B:
1. Write a program to accept a number and count number of even, odd, zero digits within that
number.
Program:
num = input("Enter a number: ")
even = odd = zeros = 0for digit in num:
d = int(digit)
if d == 0:
zeros += 1
elif d % 2 == 0:
even += 1
else:
odd += 1
print("Even digits:", even)
print("Odd digits:", odd)
print("Zero digits:", zeros)
Output:
2. Write a program to accept a binary number and convert it into decimal number.
Program:
binary = input("Enter binary number: ")
try:
decimal = int(binary, 2)
print("Decimal value:", decimal)
except ValueError:
print("Invalid binary number")
Output:
3. Write a program which accepts an integer value as command line and print “Ok” if value
is between 1 to 50 (both inclusive) otherwise it prints ”Out of range”
Program:
val = int(input("Enter a number: "))
if 1 <= val <= 50:
print("Ok")
else:
print("Out of range")
Output:
4. Write a program which accept an integer value ‘n’ and display all prime numbers till ‘n’.
Program:
n = int(input("Enter value of n: "))
print("Prime numbers till", n, ":")
for num in range(2, n + 1):
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
break
else:
print(num, end=' ')
Output:
5. Write python script to accept two numbers as range and display multiplication table of all
numbers within that range.
Program:
start = int(input("Enter start number: "))
end = int(input("Enter end number: "))
for num in range(start, end + 1):
print(f"\nTable of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
Output:
Set C:
1. Write a python script to generate the following pattern upto n lines
1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
Program:
n = int(input("Enter number of lines: "))
for i in range(1, n + 1):
print(" " * (n - i), end='')
for j in range(1, i + 1):
print(j, end=' ')
for j in range(i - 1, 0, -1):
print(j, end=' ')
print()
Output:
Assignment 2: Working with String and List
Practice Set
1. Write a python script to create a list and display the list element in
reverse order.
Program:
my_list = [1, 2, 3, 4, 5]
print("Original List:", my_list)
print("Reversed List:", my_list[::-1])
Output:
2. Write a python script to display alternate characters of string from
both the direction.
Program:
s = "PYTHONPROGRAMMING"
print("Left to Right:", s[::2])
print("Right to Left:", s[::-2])
Output:
3. Write a python program to count vowels and consonants in a string.
Program:
s = input("Enter a string: ")
vowels = "aeiouAEIOU"
v=c=0
for char in s:
if char.isalpha():
if char in vowels:
v += 1
else:
c += 1
print("Vowels:", v)
print("Consonants:", c)
Output:
Set A
1. Write a python script which accepts 5 integer values and prints “DUPLICATES” if
any of the values entered are duplicates otherwise it prints “ALL UNIQUE”.
Example: Let 5 integers are (32, 45, 90, 45, 6) then output “DUPLICATES” to be
printed.
Program:
nums = list(map(int, input("Enter 5 integers: ").split()))
if len(set(nums)) < 5:
print("DUPLICATES")
else:
print("ALL UNIQUE")
Output:
2. Write a python script to count the number of characters (character frequency) in a
string. Sample String : google.com'. Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l':
1, 'm': 1, 'c': 1}.
Program:
from collections import Counter
s = 'google.com'
freq = Counter(s)
print(freq)
Output:
3. Write a Python program to remove the characters which have odd index values of
a given string.
Program:
s = input("Enter a string: ")
result = s[::2]
print("Result:", result)
Output:
4. Write a program to implement the concept of stack using list.
Program:
stack = []
stack.append('A')
stack.append('B')
stack.append('C')
print("Stack:", stack)
print("Popped:", stack.pop())
print("Stack after pop:", stack)
Output:
5. 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.
Sample String: 'restart'
Expected Result : 'resta$t'
Program:
s = 'restart'
char = s[0]
s_new = char + s[1:].replace(char, '$')
print("Modified string:", s_new)
Output:
Set B
1. 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.
Sample String : 'General12'
Expected Result : 'Ge12'
Sample String : 'Ka'
Expected Result : 'KaKa'
Sample String : ' K'
Expected Result : Empty String
Program:
def get_string(s):
if len(s.strip()) < 2:
return ''
return s[:2] + s[-2:]
print(get_string('General12'))
print(get_string('Ka'))
print(get_string(' K'))
Output:
2. 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.
Sample String : 'abc', 'xyz'
Expected Result : 'xycabz'
Program:
def mix_strings(a, b):
new_a = b[:2] + a[2:]
new_b = a[:2] + b[2:]
return new_a + " " + new_b
print(mix_strings('abc', 'xyz'))
Output:
3. Write a Python program to count the occurrences of each word in a given sentence.
Program:
sentence = "this is a test this is only a test"
words = sentence.split()
freq = {}
for word in words:
freq[word] = freq.get(word, 0) + 1
print(freq)
Output:
4. Write a program to implement the concept of queue using list
Program:
queue = []
queue.append('A')
queue.append('B')
queue.append('C')
print("Queue:", queue)
print("Dequeued:", queue.pop(0))
print("Queue after dequeue:", queue)
Output:
5. Write a python program to count repeated characters in a string.
Sample string: 'thequickbrownfoxjumpsoverthelazydog'
Expected output: o 4 e 3 u 2 h 2 r 2 t 2
Program:
from collections import Counter
s = 'thequickbrownfoxjumpsoverthelazydog'
count = Counter(s)
for char, freq in count.items():
if freq > 1:
print(f"{char} {freq}")
Output:
Set C:
1. Write a binary search function which searches an item in a sorted list. The function
should return the index of element to be searched in the list.
Program:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == x:
return mid
elif arr[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1
arr = [1, 3, 5, 7, 9, 11]
x=7
print("Element found at index:", binary_search(arr, x))
Output:
Assignment 3: Working With Tuples, Sets and Dictionaries
Practice Set:
1. Write a Python program to add and remove operation on set.
Program:
s = {1, 2, 3}
s.add(4)
s.remove(2)
print("Set after operations:", s)
Output:
2. Write a Python program to do iteration over sets.
Program:
s = {'apple', 'banana', 'cherry'}
for item in s:
print(item)
Output:
3. Write a Python program to find the length of a set.
Program:
s = {10, 20, 30, 40}
print("Length of set:", len(s))
Output:
4. Write a Python program to create a tuple with numbers and print one item.
Program:
t = (5, 10, 15, 20)
print("Second item of tuple:", t[1])
Output:
5. Write a Python script to add a key to a dictionary.
Sample Dictionary : {0: 10, 1: 20}
Expected Result : {0: 10, 1: 20, 2: 30}
Program:
d = {0: 10, 1: 20}
d[2] = 30
print(d)
Output:
Set A:
1. Write a Python program to find maximum and the minimum value in a set.
Program:
s = {3, 6, 2, 8, 4}
print("Max:", max(s))
print("Min:", min(s))
Output:
2. Write a Python program to add an item in a tuple.
Program:
t = (1, 2, 3)
t += (4,)
print(t)
Output:
3. Write a Python program to convert a tuple to a string.
Program:
t = ('P', 'y', 't', 'h', 'o', 'n')
s = ''.join(t)
print("String:", s)
Output:
4. Write a Python program to create an intersection of sets.
Program:
a = {1, 2, 3}
b = {2, 3, 4}
print("Intersection:", a & b)
Output:
5. Write a Python program to create a union of sets.
Program:
a = {1, 2, 3}
b = {3, 4, 5}
print("Union:", a | b)
Output:
6. Write a Python script to check if a given key already exists in a dictionary.
Program:
d = {'a': 1, 'b': 2}
key = 'b'
print(key in d)
Output:
7. Write a Python script to sort (ascending and descending) a dictionary by value.
Program:
d = {'apple': 3, 'banana': 1, 'cherry': 2}
print("Ascending:", dict(sorted(d.items(), key=lambda item: item[1])))
print("Descending:", dict(sorted(d.items(), key=lambda item: item[1], reverse=True)))
Output:
Set B:
1. Write a Python program to create set difference and a symmetric difference.
Program:
a = {1, 2, 3}
b = {2, 4}
print("Difference:", a - b)
print("Symmetric Difference:", a ^ b)
Output:
2. Write a Python program to create a list of tuples with the first element as the number
and second element as the square of the number.
Program:
result = [(x, x**2) for x in range(1, 6)]
print(result)
Output:
3. Write a Python program to unpack a tuple in several variables.
Program:
t = (10, 20, 30)
a, b, c = t
print(a, b, c)
Output:
4. Write a Python program to get the 4th element from front and 4th element from last
of a tuple.
Program:
t = (1, 2, 3, 4, 5, 6, 7, 8)
print("4th from front:", t[3])
print("4th from last:", t[-4])
Output:
5. Write a Python program to find the repeated items of a tuple.
Program:
t = (1, 2, 2, 3, 4, 4, 4)
repeats = [x for x in set(t) if t.count(x) > 1]
print("Repeated items:", repeats)
Output:
6. Write a Python program to check whether an element exists within a tuple.
Program:
t = (10, 20, 30)
print(20 in t)
Output:
7. Write a Python script to concatenate following dictionaries to create a new one.
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}
Program:
dic1 = {1: 10, 2: 20}
dic2 = {3: 30, 4: 40}
dic3 = {5: 50, 6: 60}
result = {**dic1, **dic2, **dic3}
print(result)
Output:
Set C:
1. Write a Python program to create a shallow copy of sets.
Program:
s1 = {1, 2, 3}
s2 = s1.copy()
print("Original:", s1)
print("Copy:", s2)
Output:
2. Write a Python program to combine two dictionary adding values for
common keys.
d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400}
Sample output: Counter({'a': 400, 'b': 400, 'd': 400, 'c': 300})
Program:
from collections import Counter
d1 = {'a': 100, 'b': 200, 'c': 300}
d2 = {'a': 300, 'b': 200, 'd': 400}
result = Counter(d1) + Counter(d2)
print(result)
Output:
Assignment 4: Working with Functions, Modules and Packages
Practice Set:
1. Write a Python program to print Calendar of specific month of input year
using calendar module
Program:
import calendar
year = int(input("Enter year: "))
month = int(input("Enter month: "))
print(calendar.month(year, month))
Output:
2. Write a Python script to display date time in various formats using datetime module
a. Current date and time
b. Current year
c. Month of year
d. Week number of the year
e. Weekday of the week
f. Day of year
g. Day of the month
h. Day of week
Program:
import datetime
now = datetime.datetime.now()
print("Current date and time:", now)
print("Current year:", now.year)
print("Month of year:", now.strftime("%B"))
print("Week number of year:", now.strftime("%U"))
print("Weekday of the week:", now.strftime("%A"))
print("Day of year:", now.strftime("%j"))
print("Day of month:", now.day)
print("Day of week:", now.weekday()) # Monday=0, Sunday=6
Output:
3. Write an anonymous function to find area of circle.
Program:
area = lambda r: 3.14159 * r * r
print("Area of circle:", area(5))
Output:
Set A:
1. Write a recursive function which print string in reverse order.
Program:
def reverse_string(s):
if len(s) == 0:
return ""
return reverse_string(s[1:]) + s[0]
print("Reversed:", reverse_string("Python"))
Output:
2. Write a python script using function to calculate XY
Program:
def power(x, y):
return x ** y
print("Result:", power(2, 5))
Output:
3. Define a function that accept two strings as input and find union and intersection of
them.
Program:
def union_intersection(str1, str2):
set1 = set(str1)
set2 = set(str2)
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
union_intersection("hello", "world")
Output:
4. Write a recursive function to calculate sum of digits of a given input number.
Program:
def sum_digits(n):
if n == 0:
return 0
return n % 10 + sum_digits(n // 10)
print("Sum of digits:", sum_digits(1234))
Output:
5. Write generator function which generate even numbers up to n
Program:
def generate_evens(n):
for i in range(0, n+1, 2):
yield i
for num in generate_evens(10):
print(num, end=' ')
Output:
Set B:
1. Write a python script to generate Fibonacci terms using generator function.
Program:
def fib_gen(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fib_gen(7):
print(num, end=' ')
Output:
2. Write python script using package to calculate area and volume of cylinder and
cuboids.
Program:
def cylinder_area(r, h):
return 2 * 3.14 * r * (r + h)
def cuboid_volume(l, b, h):
return l * b * h
print("Cylinder Area:", cylinder_area(3, 5))
print("Cuboid Volume:", cuboid_volume(2, 3, 4))
Output:
3. Write a python script to accept decimal number and convert it to binary and octal
number using function.
Program:
def convert(num):
print("Binary:", bin(num))
print("Octal:", oct(num))
convert(25)
Output:
4. Write a function which print a dictionary where the keys are numbers between 1
and 20
(both included) and the values are square of keys
Program:
def square_dict():
d = {x: x**2 for x in range(1, 21)}
print(d)
square_dict()
Output:
5. Write a generator function which generates prime numbers up to n.
Program:
def prime_gen(n):
for num in range(2, n+1):
for i in range(2, int(num**0.5)+1):
if num % i == 0:
break
else:
yield num
for p in prime_gen(20):
print(p, end=' ')
Output:
Set C:
1. Write a program to illustrate function duck typing.
Program:
class Bird:
def fly(self):
print("Bird can fly")
class Airplane:
def fly(self):
print("Airplane can fly")
def lets_fly(flier):
flier.fly()
b = Bird()
a = Airplane()
lets_fly(b)
lets_fly(a)
Output: