Course Code-100218P
Python Programming Lab
1. Write a program to demonstrate different
number data types in Python.
Ans. num_int = 10
print(f"Value: {num_int}, Type: {type(num_int)}")
num_float = 10.5
print(f"Value: {num_float}, Type: {type(num_float)}")
num_complex = 2 + 3j
print(f"Value: {num_complex}, Type:
{type(num_complex)}")
2. Write a program to perform different
Arithmetic Operations on numbers in Python.
Ans. a = 15
b=4
print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division (Float): {a} / {b} = {a / b}")
print(f"Floor Division (Integer): {a} // {b} = {a //
b}")
print(f"Modulus (Remainder): {a} % {b} = {a % b}")
print(f"Exponentiation (Power): {a} ** {b} = {a **
b}")
3. Write a program to create, concatenate and
print a string and accessing sub-string from a
given string.
Ans. str1 = "Hello"
str2 = "World"
combined_str = str1 + " " + str2
print(f"Concatenated string: {combined_str}")
sub_str = combined_str[0:5]
print(f"Sub-string (first 5 chars): {sub_str}")
sub_str_end = combined_str[6:]
print(f"Sub-string (from index 6): {sub_str_end}")
[Link] a variable "number" and assign an
Integer to the number. Check the assigned
Integer is "Positive" or "Negative".
Ans. number = int(input("Enter an integer: "))
if number > 0:
print("Positive number")
elif number < 0:
print("Negative number")
else:
print("The number is Zero")
5. Write a program to find the largest element
among three Numbers.
Ans. num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print(f"The largest number is: {largest}")
[Link] a program to print the sum of all the
even numbers in the range 1 - 50 and print the
even sum.
Ans. even_sum = 0
for i in range(2, 51, 2):
even_sum += i
print(f"Sum of even numbers from 1 to 50 is:
{even_sum}")
7. Write a Program to display all prime
numbers within an interval of 20 and 50.
Ans. lower = 20
upper = 50
print(f"Prime numbers between {lower} and {upper}
are:")
for num in range(lower, upper + 1):
if num > 1:
is_prime = True
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
is_prime = False
break
if is_prime:
print(num)
8. Write a program to swap two numbers
without using a temporary variable.
Ans. a = 5
b = 10
print(f"Before swap: a = {a}, b = {b}")
a, b = b, a
print(f"After swap: a = {a}, b = {b}")
9. Write a program to define a function with
multiple return values.
Ans. def calculator(n1, n2):
summ = n1 + n2
diff = n1 - n2
prod = n1 * n2
return summ, diff, prod
result_sum, result_diff, result_prod =
calculator(20, 5)
print(f"Sum: {result_sum}")
print(f"Difference: {result_diff}")
print(f"Product: {result_prod}")
10. Write a python program to find factorial of a
number using Recursion.
Ans. def factorial_recursive(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial_recursive(n - 1)
num = 6
print(f"Factorial of {num} is:
{factorial_recursive(num)}")
11. Write a python script to print the current
date in the following format “WED 09 [Link]
IST 2020”.
Ans. import datetime
current_now = [Link]()
formatted_date = current_now.strftime("%a %d
%H:%M:%S IST %Y")
print(formatted_date.upper())
12. Write a Python program to convert
temperatures to and from Celsius, Fahrenheit
[Formula: c/5 = f-32/9].
Ans. def celsius_to_fahrenheit(c):
f = (c * 9/5) + 32
return f
def fahrenheit_to_celsius(f):
c = (f - 32) * 5/9
return c
c_temp = 30
f_temp = 86
print(f"{c_temp}°C is equal to
{celsius_to_fahrenheit(c_temp)}°F")
print(f"{f_temp}°F is equal to
{fahrenheit_to_celsius(f_temp)}°C")
13. Write a Python script that prints prime
numbers less than 20.
Ans. print("Prime numbers less than 20:")
for num in range(2, 20):
is_prime = True
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
is_prime = False
break
if is_prime:
print(num, end=" ")
print()
14. Write a program to print the following
patterns using loop:
Ans. rows = 4
for i in range(1, rows + 1):
for j in range(i):
print("*", end="")
print()
15. Write a program to print multiplication
tables of 8, 15, 69.
Ans. numbers = [8, 15, 69]
for num in numbers:
print(f"\nMultiplication Table of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
16. Write a program to check whether the given
input is digit or lowercase character or
uppercase character or a special character (use
'if-else-if' ladder).
Ans. char = input("Enter a single character: ")
if len(char) == 1:
if [Link]():
print("It is a digit.")
elif [Link]():
print("It is a lowercase character.")
elif [Link]():
print("It is an uppercase character.")
else:
print("It is a special character.")
else:
print("Please enter exactly one character.")
17. Write a python Program to print the
Fibonacci sequence using while loop.
Ans. n_terms = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if n_terms <= 0:
print("Please enter a positive integer")
elif n_terms == 1:
print("Fibonacci sequence upto", n_terms, ":")
print(n1)
else:
print("Fibonacci sequence:")
while count < n_terms:
print(n1, end=" ")
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
print()
18. Write a program to find the length of the
string without using any library functions.
Ans. input_string = "Hello World"
count = 0
for char in input_string:
count += 1
print(f"The length of the string '{input_string}' is:
{count}")
19. Write a program to check if two strings are
anagrams or not.
Ans. def are_anagrams(str1, str2):
s1_clean = [Link](" ", "").lower()
s2_clean = [Link](" ", "").lower()
if sorted(s1_clean) == sorted(s2_clean):
return True
else:
return False
s1 = "Listen"
s2 = "Silent"
if are_anagrams(s1, s2):
print(f"'{s1}' and '{s2}' are anagrams.")
else:
print(f"'{s1}' and '{s2}' are not anagrams.")
20. Write a program to check if the substring is
present in a given string or not. (use regular
expressions)
Ans. import re
main_string = "The quick brown fox jumps over the
lazy dog"
sub_string = "fox"
if [Link](sub_string, main_string):
print(f"Substring '{sub_string}' found in main
string.")
else:
print(f"Substring '{sub_string}' NOT found in main
string.")
21. Write a program to perform the given
operations on a list: i. add ii. Insert iii. slicing
Ans. my_list = [10, 20, 30]
print(f"Original list: {my_list}")
my_list.append(40)
print(f"After append(40): {my_list}")
my_list.insert(1, 15)
print(f"After insert(1, 15): {my_list}")
sliced_list = my_list[1:4]
print(f"Sliced list [1:4]: {sliced_list}")
22. Write a program to perform any 5 built-in
functions by taking any list.
Ans. numbers = [23, 1, 45, 12, 99, 23, 8]
print(f"Original list: {numbers}")
print(f"Length: {len(numbers)}")
print(f"Max value: {max(numbers)}")
print(f"Min value: {min(numbers)}")
print(f"Sum of elements: {sum(numbers)}")
print(f"Sorted list: {sorted(numbers)}")
23. Write a program to get a list of the even
numbers from a given list of numbers.(use only
comprehensions).
Ans. original_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = [num for num in original_list if num
% 2 == 0]
print(f"Original: {original_list}")
print(f"Even numbers: {even_numbers}")
24. Write a program to implement round robin
generator.
Ans. def round_robin(*sequences):
iterators = [iter(seq) for seq in sequences]
while iterators:
next_iterators = []
for it in iterators:
try:
yield next(it)
next_iterators.append(it)
except StopIteration:
pass
iterators = next_iterators
inputs = ([1, 2, 3], (4, 5), "AB")
rr_gen = round_robin(*inputs)
print("Round Robin Output:")
for item in rr_gen:
print(item, end=" ")
print()
25. Write a program to create tuples (name, age,
address, college) for at least two members and
concatenate the tuples and print the
concatenated tuples.
Ans. member1 = ("Alice", 20, "123 Maple St", "City
College")
member2 = ("Bob", 22, "456 Oak Ave", "State
University")
print(f"Member 1: {member1}")
print(f"Member 2: {member2}")
concatenated_tuple = member1 + member2
print(f"Concatenated Tuple: {concatenated_tuple}")
26. Write a program to return the top 'n' most
frequently occurring chars and their respective
counts.
Ans. from collections import Counter
def top_n_chars(text, n):
char_counts = Counter(text)
return char_counts.most_common(n)
sample_string = "aaaaabbbbccccdde"
n=3
result = top_n_chars(sample_string, n)
print(f"String: {sample_string}")
print(f"Top {n} frequent characters: {result}")
27. Write a program to count the number of
vowels in a string (No control flow allowed).
Ans. text = "Python Programming is Fun"
vowels_list = [char for char in [Link]() if char in
'aeiou']
vowel_count = len(vowels_list)
print(f"String: {text}")
print(f"Number of vowels: {vowel_count}")
28. Write a program that displays which letters
are present in both strings.
Ans. str1 = "apple"
str2 = "pear"
set1 = set(str1)
set2 = set(str2)
common_letters = set1 & set2
print(f"String 1: {str1}")
print(f"String 2: {str2}")
print(f"Letters present in both: {common_letters}")
29. Write a program to sort given list of strings
in the order of their vowel counts.
Ans. def count_vowels(word):
vowels = 'aeiouAEIOU'
return len([char for char in word if char in vowels])
words_list = ["banana", "apple", "kiwi", "orange", "a"]
sorted_words = sorted(words_list, key=count_vowels)
print("Sorted by vowel count:")
for word in sorted_words:
print(f"{word} (Vowels: {count_vowels(word)})")
30. Write a program to generate a dictionary
that contains numbers (between 1 and n) in the
form of (x, x*x).
Ans. n = 5
squares_dict = {x: x*x for x in range(1, n + 1)}
print(f"Dictionary of squares up to {n}:")
print(squares_dict)
31. Write a program to check if a given key exists
in a dictionary or not.
Ans. my_dict = {'name': 'John', 'age': 25, 'city': 'New
York'}
key_to_check = 'age'
if key_to_check in my_dict:
print(f"Key '{key_to_check}' exists in dictionary.")
else:
print(f"Key '{key_to_check}' does not exist in
dictionary.")
32. Write a program to add a new key-value pair
to an existing dictionary.
Ans. student = {'name': 'Emma', 'grade': 'A'}
print(f"Original dictionary: {student}")
student['subject'] = 'Computer Science'
print(f"Updated dictionary: {student}")
33. Write a program to sum all the items in a
given dictionary.
Ans. data_dict = {'a': 100, 'b': 250, 'c': 50}
total_sum = sum(data_dict.values())
print(f"Dictionary: {data_dict}")
print(f"Sum of all values: {total_sum}")
34. Write a program to sort words in a file and
put them in another file. The output file should
have only lower case words, so any upper case
words from source must be lowered. (Handle
exceptions)
Ans. try:
with open("[Link]", "w") as f:
[Link]("Zebra Apple Orange Banana apple")
with open("[Link]", "r") as source_file:
content = source_file.read()
words = [[Link]() for word in [Link]()]
[Link]()
with open("output_sorted.txt", "w") as dest_file:
for word in words:
dest_file.write(word + "\n")
print("Words sorted and written to output_sorted.txt
successfully.")
except FileNotFoundError:
print("Error: The source file was not found.")
except IOError as e:
print(f"An I/O error occurred: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
35. Write a program to find the most frequent
words in a text. (read from a text file).
Ans. from collections import Counter
import re
try:
with open("sample_text.txt", "w") as f:
[Link]("Python is great. Python is dynamic. Python
is fun.")
with open("sample_text.txt", "r") as file:
text = [Link]().lower()
words = [Link](r'\b\w+\b', text)
word_counts = Counter(words)
most_common = word_counts.most_common(3)
print("Most frequent words:")
for word, count in most_common:
print(f"'{word}': {count} times")
except FileNotFoundError:
print("File not found.")