Python Lab Mannual
Python Lab Mannual
DEPARTMENT OF
PYTHON PROGRAMMING
LAB MANUAL
Regulation: R-22
1
Course Objectives:
To install and run the Python interpreter
To learn control structures.
To Understand Lists, Dictionaries in python
To Handle Strings and Files in Python
Course Outcomes:
After completion of the course, the student should be able to
● Develop the application specific codes using python.
● Understand Strings, Lists, Tuples and Dictionaries in Python
● Verify programs using modular approach, file I/O, Python standard library
● Implement Digital Systems using Python
Note: The lab experiments will be like the following experiment examples
2
LIST OF EXPERIMENTS:
Week -1:
1. i) Use a web browser to go to the Python website http://python.org. This page contains information about
Python and links to Python-related pages, and it gives you the ability to search the Python
ii) Start the Python interpreter and type help() to start the online help utility.
3. i) Write a program to calculate compound interest when principal, rate and number of periods are given.
ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points
4. Read name, address, email and phone number of a person through keyboard and print the details.
Week - 2:
1. Print the below triangle using for loop.
5
44
333
2222
11111
2. Write a program to check whether the given input is digit or lowercase character or uppercase character or
4. Python program to print all prime numbers in a given interval (use break)
Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
2. Write a function called gcd that takes parameters a and b and returns their greatest common divisor.
3. Write a function called palindrome that takes a string argument and returnsTrue if it is a palindrome and
3
False otherwise. Remember that you can use the built-in function len to check the length of a string.
Week - 4:
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in
ascending order and False otherwise.
2. Write a function called has_duplicates that takes a list and returns True if there is any element that appears
more than once. It should not modify the original list.
i). Write a function called remove_duplicates that takes a list and returns a new list with only the unique
elements from the original. Hint: they don’t have to be in the same order.
ii). The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add “I”,
“a”, and the empty string.
iii). Write a python code to read dictionary values from the user. Construct a function to invert its
content. i.e., keys should be values and values should be keys.
3. i) Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,e'
iii) Write a function that takes a sentence as an input parameter and replaces the first letter of every word
with the corresponding upper case letter and the rest of the letters in the word by corresponding letters in
lower case without using a built-in function?
4. Writes a recursive function that generates all binary strings of n-bit length
Week - 5:
1. i) Write a python program that defines a matrix and prints
2. How do you make a module? Give an example of construction of a module using different geometrical
shapes and operations on them as its functions.
4
Week-6:
1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as arguments and draws
a representation of the Rectangle on the Canvas.
b. Add an attribute named colour to your Rectangle objects and modify draw_rectangle so that it uses the
color attribute as the fill color.
c. Write a function called draw point that takes a Canvas and a Point as arguments and draws a
representation of the Point on the Canvas.
d. Define a new class called Circle with appropriate attributes and instantiate a few Circle objects. Write a
function called draw circle that draws circles on the canvas.
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in multiple
levels of Inheritances.
3. Write a python code to read a phone number and email-id from the user and validate it for correctness.
Week- 7
1. Write a Python code to merge two given file contents into a third file.
2. Write a Python code to open a given file and construct a function to check for given words present in it
and display on found.
3. Write a Python code to Read text from a text file, find the word with most number of occurrences
4. Write a function that reads a file file1 and displays the number of words, number of vowels, blank
spaces, lower case letters and uppercase letters.
Week - 8:
1. Import numpy, Plotpy and Scipy and explore their functionalities.
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
5
5. Write a GUI program to create a window wizard having two text labels, two text fields and two
buttons as Submit and Reset
TEXT BOOKS:
1. Supercharged Python: Take your code to the next level, Overland
2. Learning Python, Mark Lutz, O'reilly
REFERENCE BOOKS:
1. Python Programming: A Modern Approach, Vamsi Kurama, Pearson
2. Python Programming A Modular Approach with Graphics, Database, Mobile, and Web Applications,
Sheetal Taneja, Naveen Kumar, Pearson
3. Programming with Python, A User’s Book, Michael Dawson, Cengage Learning, India Edition
4. Think Python, Allen Downey, Green Tea Press
5. Core Python Programming, W. Chun, Pearson
6. Introduction to Python, Kenneth A. Lambert, Cengage
6
Week -1:
1. i) Use a web browser to go to the Python website http://python.org. This page contains information
about Python and links to Python-related pages, and it gives you the ability to search the Python
documentation.
Once you are on the Python website, you can explore the various sections, such as the Python documentation,
tutorials, downloads, and community resources. The website provides valuable information about Python
programming language and related resources. Additionally, you can use the search functionality available on
the Python website to search the Python documentation for specific topics or functions.
ii) Start the Python interpreter and type help() to start the online help utility.
To start the Python interpreter and access the online help utility, you can follow these steps:
1. Open your preferred Python interpreter on your local machine. This could be the Python interactive
shell (command prompt or terminal) or an integrated development environment (IDE) like IDLE,
PyCharm, or Jupyter Notebook.
2. Once you have the Python interpreter running, type help() and press Enter.
After executing the help() command, you will enter the online help utility, where you can navigate through
the available topics and access information about Python functions, modules, and syntax. You can enter
specific topics or function names to get detailed help and usage examples.
Please note that the specific features and behavior of the online help utility may vary slightly depending on
the Python version and the environment you are using.
7
2. Start a Python interpreter and use it as a Calculator.
Certainly! You can use the Python interpreter as a calculator to perform various mathematical calculations. Here's how
you can start a Python interpreter and use it for basic arithmetic operations:
1. Open a Python interpreter on your local machine. This could be the Python interactive shell (command prompt
or terminal) or an integrated development environment (IDE) with a Python console.
2. Once you have the Python interpreter running, you can start performing calculations. Here are some examples
of basic arithmetic operations you can try:
Addition
>>> 2 + 3
5
Subtraction:
>>> 5 - 2
3
Multiplication:
>>> 4 * 6
24
Division
>>> 10 / 3
3.3333333333333335
Floor Division (integer division):
>>> 10 // 3
3
Exponentiation:
>>> 2 ** 4
16
Modulo (remainder):
>>> 17 % 5
2
3.You can also use parentheses to group operations and control the order of evaluation:
>>> (4 + 5) * 2
18
4.Feel free to experiment with more complex calculations and mathematical functions. For example, you can use
functions from the math module for advanced mathematical operations such as square roots, trigonometric functions,
logarithms, etc. To use the math module, you need to import it first:
>>> import math
>>>math.sqrt(25)
5.0
8
Remember that the Python interpreter follows the usual precedence rules for arithmetic operations (e.g., multiplication
and division are performed before addition and subtraction). You can use parentheses to override the default
precedence and enforce the desired order of evaluation.
I hope this helps you get started with using the Python interpreter as a calculator!
3. i) Write a program to calculate compound interest when principal, rate and number of periods are given.
Certainly! Here's a Python program that calculates compound interest based on the principal amount, interest rate, and
the number of periods:
return compound_interest
# Example usage
principal = 1000
rate = 5
periods = 3
In this program, the `calculate_compound_interest` function takes in three parameters: `principal` (the initial amount),
`rate` (the interest rate in percentage), and `periods` (the number of compounding periods).
Inside the function, the interest rate is converted from a percentage to a decimal by dividing it by 100. Then, the
compound interest is calculated using the formula: `principal * (1 + rate) ** periods - principal`. The result is returned
by the function.
In the example usage, the program calculates the compound interest for a principal amount of 1000, an interest rate of
5%, and 3 compounding periods. The result is printed as "Compound Interest: [value]".
3 i) Write a program to calculate compound interest when principal, rate and number of periods are given
# inputs
p=1200 # principal amount
t=2 # time
r=5.4 # rate
# calculates the compound interest
a=p*(1+(r/100))**t # formula for calculating amount
ci=a-p # compound interest = amount - principal amount
# printing compound interest value
print(ci)
Output
9
133.0992000000001
principal = int(input("Enter Principal:"))
CI = amount - principal
CI = amount - principal
OUTPUT
Enter Principal:50000
3 ii) Given coordinates (x1, y1), (x2, y2) find the distance between two points in python
To find the distance between two points with coordinates (x1, y1) and (x2, y2), you can use the distance formula
derived from the Pythagorean theorem. The formula is:
Let's apply this formula to find the distance between two points.
To find the distance between two points given their coordinates (x1, y1) and (x2, y2), you can use the distance formula,
also known as the Euclidean distance formula. The formula is derived from the Pythagorean theorem and calculates the
straight-line distance between the two points in a two-dimensional space.
10
The distance formula is:
By substituting the given coordinates into the formula, you can calculate the distance.
Let's assume the coordinates are (x1, y1) = (2, 4) and (x2, y2) = (6, 8). We can plug these values into the formula:
Distance = sqrt((6 - 2)^2 + (8 - 4)^2) = sqrt(4^2 + 4^2) = sqrt(16 + 16) = sqrt(32) ≈ 5.657
Therefore, the distance between the points (2, 4) and (6, 8) is approximately 5.657 units.
import math
return distance
# Example usage
x1 = 1
y1 = 2
x2 = 4
y2 = 6
print("Distance:", distance)
import math
x1, y1 = map(int, input("Enter the coordinates of first point").split())
OUTPUT
Enter the coordinates of first point3 2
11
Enter the coordinates of second point9 7
print("Name:", name)
print("Address:", address)
print("Email:", email)
In this program, the `input()` function is used to prompt the user to enter their name, address, email, and
phone number. Each input is assigned to a corresponding variable (`name`, `address`, `email`, and
`phone_number`).
Then, the program uses the `print()` function to display the details entered by the user. The output will
include the labels "Name:", "Address:", "Email:", and "Phone Number:", followed by the values entered by
the user.
When you run this program, it will display the prompts on the console, and you can enter your details one by
one. After entering the information, the program will print out the entered details.
Week - 2:
1. Print the below triangle using for loop.
12
5
44
333
2222
11111
Certainly! Here's a Python program that uses a for loop to print the triangle pattern you mentioned
When you run this program, it will output the following triangle pattern:
5
44
333
2222
11111
In the outer loop, we iterate from 5 to 1 in descending order using the `range()` function with the step value
of -1.
In the inner loop, we iterate from 0 to `i-1` (the current value of the outer loop variable) using the `range()`
function. This inner loop is responsible for printing the number `i` multiple times in each row.
The `end=' '` argument in the `print()` function is used to print the numbers in the same line, separated by a
space.
Finally, the `print()` statement without any arguments is used to move to a new line after printing each row.
Feel free to modify the range or adjust the formatting to match your requirements.
num=n
for i in range(n):
for j in range(i+1):
num=num-1
13
print()
2. 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)
Here's a Python program that uses an if-else-if ladder to check whether the given input is a digit, lowercase character,
uppercase character, or a special character:
if input_char.isdigit():
print("Input is a digit.")
elifinput_char.islower():
elifinput_char.isupper():
else:
In this program, the user is prompted to enter a character. The input is stored in the `input_char` variable.
The program then uses an if-else-if ladder to check the type of character. The `isdigit()` method checks if the input is a
digit, the `islower()` method checks if the input is a lowercase character, and the `isupper()` method checks if the input
is an uppercase character. If none of these conditions are met, it is considered a special character.
Based on the type of character, the program will print the corresponding message.
For example, if you enter "A", the program will output: "Input is an uppercase character." If you enter "5", the program
will output: "Input is a digit." If you enter "#", the program will output: "Input is a special character."
s=input(“Enter a character:”)
if s.isdigit():
elifs.islower():
elifs.isupper():
else:
14
print("Given input is a special character")
OUTPUT
Enter a character:5
Enter a character:k
Enter a character:B
Given input is an upper case character
Enter a character:$
Given input is a special character
Input the number of values we want to generate the Fibonacci sequence and initialize a=0, b=1, sum=0, and count=1. Start a while
loop using the condition count<=n and print the sum every time the condition works. Increment the count variable, swap 'a' and 'b,'
and store the addition of a and b in the sum.
n1, n2 = 0, 1
count = 0
if nterms<= 0:
elifnterms == 1:
print(n1)
# generatefibonacci sequence
else:
print("Fibonacci sequence:")
print(n1)
nth = n1 + n2
# update values
15
n1 = n2
n2 = nth
count += 1
OUTPUT:
0
1
1
2
3
5
8
13
n=int(input(“Enter no.of rows in the Fibonacci sequence:”))
n1=0 n2=1
print(n1,n2,end=" ")
while (n-2)!=0:
n3=n1+n2
n1=n2
n2=n3
print(n3,end=" ")
n=n-1
OUTPUT
Enter no.of terms of the Fibonacci sequence:8
0 1 1 2 3 5 8 13
4. Python program to print all prime numbers in a given interval (use break)
In this program, the user is prompted to enter the lower and upper bounds of the interval. These values
are stored in the variables `lower` and `upper`, respectively.
The program then uses a nested for loop structure to iterate through each number in the given interval.
For each number, it checks if it is greater than 1. If it is, it enters another loop to check if the number is
divisible by any number from 2 to `num - 1`.
If the number is divisible by any of these numbers, the `break` statement is encountered, which
terminates the inner loop. This means that the number is not prime, and the program moves on to the
next number.
If the inner loop completes without encountering a `break` statement, it means that the number is not
divisible by any number from 2 to `num - 1`. In this case, the number is considered prime and is printed.
The program will print all the prime numbers found within the given interval.
beg = int(input("Enter the beginning number of the range: "))
if i> 1:
for j in range(2,i):
if i%j==0:
break
else:
OUTPUT
17
Week - 3:
1. i) Write a program to convert a list and tuple into arrays.
To convert a list and tuple into arrays, you can use the NumPy library in Python. Here's an example program
that demonstrates how to do this:
import numpy as np
def convert_to_array(data):
if isinstance(data, list):
return np.array(data)
elifisinstance(data, tuple):
return np.array(data)
else:
# Example usage
my_list = [1, 2, 3, 4, 5]
list_array = convert_to_array(my_list)
print("List to array:")
print(list_array)
tuple_array = convert_to_array(my_tuple)
print("Tuple to array:")
print(tuple_array)
In this program, the `convert_to_array` function checks the type of the input data. If it is a list or tuple, it uses
the `np.array()` function from NumPy to convert it into an array. Finally, it returns the array. If the input data
is neither a list nor a tuple, it displays an error message.
Running the above program will give you the converted arrays for both the list and tuple.
18
from array import array
t_arr = array("i", t)
print(type(l_arr))
print(type(t_arr))
OUTPUT
Enter elements of list:10 20 30 40
<class 'array.array'>
<class 'array.array'>
To find the common values between two arrays in Python, you can use the NumPy library. Here's an example program
that demonstrates how to do this:
import numpy as np
return common_values
# Example usage
print("Common values:")
print(common_values)
In this program, the `find_common_values` function takes two arrays as input. It uses the `np.intersect1d()` function
from NumPy to find the common values between the two arrays. The function then returns the common values.
Running the above program will give you the common values between `array1` and `array2`. In this example, the
common values are `[4, 5]`.
2. Write a function called gcd that takes parameters a and b and returns their greatest common
divisor.
Certainly! Here's a Python function called `gcd` that calculates the greatest common divisor (GCD)
of two numbers `a` and `b` using the Euclidean algorithm:
if a < b:
a, b = b, a
# Euclidean algorithm
while b != 0:
a, b = b, a % b
return a
In this function, we first ensure that `a` is greater than or equal to `b` by swapping their values if necessary.
Then, we use the Euclidean algorithm to iteratively calculate the remainder of `a` divided by `b` until `b`
becomes 0. The last non-zero remainder, stored in `a`, is the GCD of the two numbers.
You can call the `gcd` function with your desired values of `a` and `b` to find their greatest common divisor.
For example:
a = 36
b = 48
result = gcd(a, b)
Output:
20
The function will return the GCD of `a` and `b`, which in this case is 12.
3.Write a function called palindrome that takes a string argument and returnsTrue if it is a palindrome and
False otherwise. Remember that you can use the built-in function len to check the length of a string.
Sure! Here's a Python function called `palindrome` that checks if a string is a palindrome:
def palindrome(string):
if string == string[::-1]:
return True
else:
return False
In this function, we first remove any whitespace from the string and convert it to lowercase using the
`replace()` and `lower()` string methods, respectively. Then, we compare the string with its reverse (`string[::-
1]`) to check if they are equal.
You can call the `palindrome` function with your desired string to check if it's a palindrome. For example:
result = palindrome(input_string)
Output:
The function will return `True` if the string is a palindrome and `False` otherwise. In this example, the input
string "A man a plan a canal Panama" is a palindrome, so the result is `True`.
21
Week - 4:
1. Write a function called is_sorted that takes a list as a parameter and returns True if the list is sorted in
ascending order and False otherwise.
Certainly! Here's a Python function called `is_sorted` that checks if a list is sorted in ascending order:
def is_sorted(lst):
return lst == sorted(lst)
In this function, we compare the original list `lst` with the sorted version of the list using the `sorted()`
function. If the two lists are equal, it means that the original list is sorted in ascending order, so the function
returns `True`. Otherwise, it returns `False`.
You can call the `is_sorted` function with your desired list to check if it's sorted in ascending order.
For example:
my_list = [1, 2, 3, 4, 5]
result = is_sorted(my_list)
print("Is the list sorted?", result)
Output:
Is the list sorted? True
The function will return `True` if the list is sorted in ascending order and `False` otherwise. In this example,
the input list `[1, 2, 3, 4, 5]` is sorted, so the result is `True`.
2. Write a function called has_duplicates that takes a list and returns True if there is any element that
appears more than once. It should not modify the original list.
Certainly! Here's a Python function called `has_duplicates` that checks if a list has any duplicate elements
without modifying the original list:
def has_duplicates(lst):
# Create a set to store unique elements
unique_elements = set()
for element in lst:
# Check if element is already in the set
if element in unique_elements:
return True
else:
unique_elements.add(element)
return False
22
In this function, we iterate over each element in the list. We use a set, `unique_elements`, to keep track of the
unique elements encountered so far. If an element is already in the set, it means it's a duplicate, and we return
`True`. If we finish iterating through the list without finding any duplicates, we return `False`.
You can call the `has_duplicates` function with your desired list to check if it has any duplicate elements. For
example:
my_list = [1, 2, 3, 4, 5]
result = has_duplicates(my_list)
print("Does the list have duplicates?", result)
Output:
Does the list have duplicates? False
The function will return `True` if the list has any duplicate elements and `False` otherwise. In this example,
the input list `[1, 2, 3, 4, 5]` doesn't have any duplicates, so the result is `False`.
i). Write a function called remove_duplicates that takes a list and returns a new list with only the
unique elements from the original. Hint: they don’t have to be in the same order.
Certainly! Here's a Python function called `has_duplicates` that checks if a list has any duplicate elements
without modifying the original list:
def has_duplicates(lst):
unique_elements = set()
if element in unique_elements:
return True
else:
unique_elements.add(element)
return False
In this function, we iterate over each element in the list. We use a set, `unique_elements`, to keep track of the
unique elements encountered so far. If an element is already in the set, it means it's a duplicate, and we return
`True`. If we finish iterating through the list without finding any duplicates, we return `False`.
You can call the `has_duplicates` function with your desired list to check if it has any duplicate elements. For
example:
my_list = [1, 2, 3, 4, 5]
result = has_duplicates(my_list)
23
print("Does the list have duplicates?", result)
Output:
The function will return `True` if the list has any duplicate elements and `False` otherwise. In this example,
the input list `[1, 2, 3, 4, 5]` doesn't have any duplicates, so the result is `False`.
ii). The wordlist I provided, words.txt, doesn’t contain single letter words. So you might want to add
“I”, “a”, and the empty string.
If the wordlist provided in "words.txt" doesn't contain single-letter words like "I", "a", and the empty string,
we can modify the `remove_duplicates` function to include them. Here's an updated version of the function:
def remove_duplicates(lst):
# Create a set to store unique elements
unique_elements = set(lst)
# Add single-letter words if not present in the set
unique_elements.update(['I', 'a', ''])
# Convert the set back to a list
unique_list = list(unique_elements)
return unique_list
In this updated function, we first create a set, `unique_elements`, to store the unique elements from the list.
Then, we use the `update()` method of the set to add the single-letter words "I", "a", and the empty string.
Finally, we convert the set back to a list, `unique_list`, to return the result.
You can call the updated `remove_duplicates` function with your desired list to get a new list with only the
unique elements, including the single-letter words. For example:
my_list = ['apple', 'banana', 'banana', 'cherry']
result = remove_duplicates(my_list)
print("List with duplicates removed:", result)
Output:
List with duplicates removed: ['', 'cherry', 'banana', 'I', 'apple', 'a']
As you can see, the function now includes the single-letter words "I", "a", and the empty string in the
resulting list, along with the other unique elements.
iii). Write a python code to read dictionary values from the user. Construct a function to invert its
content. i.e., keys should be values and values should be keys.
Certainly! Here's a Python code that reads dictionary values from the user and constructs a function to invert
its content, where the keys become values and the values become keys:
def invert_dictionary(dictionary):
24
inverted_dict = {}
for key, value in dictionary.items():
inverted_dict[value] = key
return inverted_dict
# Read dictionary values from the user
dictionary = {}
num_entries = int(input("Enter the number of entries in the dictionary: "))
for i in range(num_entries):
key = input("Enter key: ")
value = input("Enter value: ")
dictionary[key] = value
# Invert the dictionary
inverted_dictionary = invert_dictionary(dictionary)
# Print the inverted dictionary
print("Inverted dictionary:")
for key, value in inverted_dictionary.items():
print(key, ":", value)
In this code, we first define the `invert_dictionary` function that takes a dictionary as input. It iterates through
the key-value pairs of the dictionary and constructs a new dictionary, `inverted_dict`, where the values
become keys and the keys become values.
The code then reads dictionary values from the user by asking for the number of entries and key-value pairs.
It stores the input values in the `dictionary` dictionary.
Next, it calls the `invert_dictionary` function, passing the `dictionary` as an argument, to obtain the inverted
dictionary in the `inverted_dictionary` variable.
Finally, it prints the inverted dictionary, displaying each key-value pair.
You can run this code and enter the dictionary values as prompted to obtain the inverted dictionary.
3i) Add a comma between the characters. If the given word is 'Apple', it should become 'A,p,p,l,eSure!
Below is a Python program that takes a word as input and adds a comma between each character to
create the modified word:
def add_comma_between_characters(word):
modified_word = ','.join(word)
return modified_word
# Test the function
25
input_word = 'Apple'
modified_word = add_comma_between_characters(input_word)
print(modified_word)
When you run this program with the input word 'Apple', it will output:
A,p,p,l,e
The `join()` method is used to join the characters of the word with a comma in between.
ii) Remove the given word in all the places in a string?
To remove all occurrences of a given word from a string in Python, you can use the `replace()` method.
Here's a Python program that demonstrates how to achieve this:
def remove_word_from_string(input_string, word_to_remove):
modified_string = input_string.replace(word_to_remove, "")
return modified_string
# Test the function
input_string = "This is a sample sentence containing the word sample. Another sample."
word_to_remove = "sample"
modified_string = remove_word_from_string(input_string, word_to_remove)
print(modified_string)
In this program, we define the `remove_word_from_string()` function that takes two arguments:
`input_string`, which is the original string, and `word_to_remove`, which is the word you want to remove
from the string. The function uses the `replace()` method to replace all occurrences of the given word with an
empty string, effectively removing it.
When you run this program with the input string and word as shown above, it will output:
This is a sentence containing the word . Another .
As you can see, all occurrences of the word "sample" have been removed from the original string.
iii) Write a function that takes a sentence as an input parameter and replaces the first letter of every
word with the corresponding upper case letter and the rest of the letters in the word by
corresponding letters in lower case without using a built-in function?
You can achieve this by defining a function that manually converts the first letter of each word to uppercase
and the rest of the letters to lowercase. Here's a Python function that does that:
def capitalize_first_letter(sentence):
words = sentence.split()
modified_sentence = ""
for word in words:
if len(word) > 0:
26
first_letter = word[0].upper()
rest_of_word = word[1:].lower()
modified_word = first_letter + rest_of_word
modified_sentence += modified_word + " "
# Remove the trailing space at the end of the modified sentence
modified_sentence = modified_sentence.strip()
return modified_sentence
# Test the function
input_sentence = "tHis is A saMplesENTeNce"
modified_sentence = capitalize_first_letter(input_sentence)
print(modified_sentence)
In this program, we define the `capitalize_first_letter()` function that takes a sentence as input. Inside the
function, we first split the sentence into individual words using the `split()` method. Then, for each word, we
extract the first letter, convert it to uppercase using the `upper()` method, and convert the rest of the word to
lowercase using the `lower()` method. Finally, we concatenate the modified word back into the
`modified_sentence` variable.
When you run this program with the input sentence as shown above, it will output:
This is a sample sentence
As you can see, the function correctly capitalizes the first letter of each word and converts the rest of the
letters to lowercase.
4.Writes a recursive function that generates all binary strings of n-bit length
To generate all binary strings of n-bit length using a recursive function in Python, you can follow this
approach:
def generate_binary_strings(n):
if n == 0:
return ['']
else:
previous_strings = generate_binary_strings(n - 1)
new_strings = []
for string in previous_strings:
new_strings.append(string + '0')
new_strings.append(string + '1')
return new_strings
27
# Test the function
n_bits = 3
binary_strings = generate_binary_strings(n_bits)
print(binary_strings)
In this recursive function `generate_binary_strings(n)`, we have a base case when `n` becomes 0, where we
return a list containing an empty string `['']`. For `n` greater than 0, we call the function recursively with `n-1`
and then append '0' and '1' to each of the returned strings to create new strings.
When you run the program with `n_bits = 3`,
it will output:
['000', '001', '010', '011', '100', '101', '110', '111']
These are all the possible binary strings of length 3. The function will work for any positive integer value of
`n` to generate all binary strings of `n`-bit length.
WEEK-5
1.i) Write a python program that defines a matrix and prints
# A basic code for matrix input from user
a =[]
a.append(int(input()))
matrix.append(a)
for i in range(R):
for j in range(C):
print()
28
Output:
Enter the number of rows:2
Enter the number of columns:3 Enter the entries row
wise:
1
2
3
4
5
6
123
456
X = [[1,2,3],
[4 ,5,6],
[7 ,8,9]]
Y = [[9,8,7],
[6,5,4],
[3,2,1]]
[4, 5, 6],
[7, 8, 9]]
[6, 7, 3, 0],
29
[4, 5, 9, 1]]
result= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
result = np.dot(A,B)
for r in result:
print(r)
Output:
[74 97 73 14]
2. How do you make a module? Give an example of construction of a module using different
geometrical shapes and operations on them as its functions.
# shapes.py - a module for working with basic shapes import math
def area_circle(radius):
"""Returns the area of a circle with the given radius""" return math.pi *
radius ** 2
def area_rectangle(length, width):
"""Returns the area of a rectangle with the given length and width""" return length *
width
def area_triangle(base, height):
"""Returns the area of a triangle with the given base and height""" return 0.5 * base *
height
def perimeter_circle(radius):
"""Returns the perimeter of a circle with the given radius""" return 2 * math.pi
* radius
def perimeter_rectangle(length, width):
"""Returns the perimeter of a rectangle with the given length and width""" return 2 * (length
+ width)
def perimeter_triangle(side1, side2, side3):
"""Returns the perimeter of a triangle with the given side lengths""" return side1 +
side2 + side3
30
In this example, we've defined a module called shapes that contains six functions for calculating the area and
perimeter of circles, rectangles, and triangles. These functions take different parameters depending on the
shape and return the corresponding area or perimeter.
To use this module in another program, we can import it like this:
import shapes
print(shapes.area_circle(2))
print(shapes.perimeter_rectangle(4, 5))
# Output: 12.566370614359172
# Output: 18
3. Use the structure of exception handling all general purpose exceptions. try:
even_numbers = [2,4,6,8]
print(even_numbers[5])
WEEK – 6
1. a. Write a function called draw_rectangle that takes a Canvas and a Rectangle as arguments and draws a
representation of the Rectangle on the Canvas.
31
drawn_canvas = world.ca(canvas.width, canvas.height)
drawn_canvas.rectangle(rectangle.bbox, fill=rectangle.color)
world = World()
draw_rectangle(a_canvas,box)
world.mainloop()
Output:
b. Add an attribute named color to your Rectangle objects and modify draw_rectangle so that it uses the color
attribute as the fill color.
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500
32
drawn_canvas.rectangle(rectangle.bbox, fill=rectangle.color)
world = World()
draw_rectangle(a_canvas,box)
world.mainloop()
Output:
c. Write a function called draw_point that takes a Canvas and a Point as arguments and draws a representation
of the Point on the Canvas.
a_canvas = Canvas()
a_canvas.width = 500
a_canvas.height = 500
p= Point() p.x = 60
p.y = 15
33
bbox = [[point.x, point.y], [point.x, point.y]]
world = World()
draw_point(a_canvas,p)
world.mainloop()
Output:
d. Define a new class called Circle with appropriate attributes and instantiate a few Circle objects. Write a
function called draw_circle that draws circles on the canvas.
from swampy.World import *
a_canvas.height = 500
c = Circle()
c.radius = 50
c.center = Point()
c.center.x = 20
c.center.y = 20
34
def draw_circle(canvas, circle): drawn_canvas =
world.ca(canvas.width, canvas.height)
world = World()
draw_circle(a_canvas,c)
world.mainloop()
Output:
2. Write a Python program to demonstrate the usage of Method Resolution Order (MRO) in multiple levels of
Inheritances.
class A(object):
def method(self):
print("A class method")
super().method()
class B(object):
def method(self):
super().method()
class C(object):
def method(self):
print("C class method")
class X(A,B):
35
def method(self):
super().method()
class Y(B,C):
def method(self):
print("Y class method")
super().method()
class P(X,Y,C):
def method(self):
super().method()
pobj=P()
pobj.method()
Output:
P class method
X class method
Valid Number
Enter Email-ID:mruthyunjay.m@gmail.com
Valid Email
Invalid Number
Enter Email-ID:jayforpython@.com
Invalid Email
36
WEEK-7
1. Write a Python code to merge two given file contents into a third file.
The following are steps to merge.
1. Open file1.txt and file2.txt in read mode.
2. Open file3.txt in write mode.
3. Read the data from file1 and add it in a string.
4. Read the data from file2 and concatenate the data of this file to the previous string.
5. Write the data from string to file3
6. Close all the files
Note: To successfully run the below program file1.txt and file2.txt must exist in the same folder. Suppose the
text files file1.txt and file2.txt contain the following data.
File1.txt
Hello Folks, Welcome to File Handling!
This is the content of File1.txt
File2.txt
Hello Techies, Let’s do more Hands-n Coding
This is the content of File2.txt
# Python program to
# demonstrate merging
# of two files
# Merging 2 files
# To add the data of file2 # from next
line data += "\n"
data += data2
with open ('file3.txt', 'w') as fp:
fp.write(data)
Output:
File3.txt will be created with the following content
Hello Folks, Welcome to File Handling!
37
This is the content of File1.txt
Hello Techies, Let’s do more Hands-n Coding
This is the content of File2.txt
2. Write a Python code to open a given file and construct a function to check for given words present in it and
display on found.
if word in file_contents:
found_words.append(word) if found_words:
print(word) else:
# Example usage:
file_path = "example_file.txt"
find_words(file_path, words_to_find)
Output:
Found the following words in the file: apple banana
orange
3. Write a Python code to Read text from a text file, find the word with most number of occurrences
38
with open('example_file.txt', 'r') as file:
text = file.read()
# Loop through each word and count the number of occurrences for word in
words: if word in word_counts: word_counts[word] += 1 else:
word_counts[word] = 1
occurrences.".format(most_common_word, word_counts[most_common_word]))
Output:
The word with the most number of occurrences is 'apple' with 8 occurrences.
4. Write a function that reads a file file1 and displays the number of words, number of vowels, blank spaces,
lower case letters and uppercase letters.
def analyze_file(file_name):
data = f.read()
word_count = len(data.split())
39
# Count the number of blank spaces
'word_count': word_count,
'vowel_count': vowel_count,
'space_count': space_count,
'lowercase_count': lowercase_count,
'uppercase_count': uppercase_count
Output :
'uppercase_count': 1}
WEEK - 8
numpy(Numerical Python):
numpy is a package that contains several classes, functions, variables etc., to deal with scientific calculations
in Python
numpy is useful to create and also process signle and multi-dimensional arrays. In addition, numpy contains a
large library of mathematical functions like linear argebra functions and fourier transforms.
To install numpy
40
pip install numpyTo install Scipy
Output:
[10 20 30 40 50]
Output:
print("Expression value:",(arr+5)**2-10)
Output:
3. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
1. AND Gate
42
The AND gate gives an output of 1 if both the two inputs are 1, it gives 0 otherwise.
if a == 1 and b == 1:
return False
Output:
True
3. OR Gate
43
The OR gate gives an output of 1 if either of the two inputs are 1, it gives 0 otherwise.
# working of OR gate
return False
Output:
False
+---------------+----------------+
5. NOT Gate
It acts as an inverter. It takes only one input. If the input is given as 1, it will invert the result as 0 and vice-versa.
return not a
print(NOT(0))
Output:
1
+---------------+----------------+
| NOT Truth Table | Result |
A = False | A NOT = 1 |
A = True, | A NOT = 0 |
4. XOR Gate
The XOR gate gives an output of 1 if either of the inputs is different, it gives 0 if they are the same.
return 1 else:
return 0
Output:
+---------------+----------------+
| XOR Truth Table | Result |
A = False, B = False | A XOR B = 0 | A = False, B = True |
A XOR B = 1 | A = True, B = False | A XOR B = 1 |
A = True, B = True | A XOR B = 0 |
4. Write a program to implement Half Adder, Full Adder, and Parallel Adder
45
Given two inputs of Half Adder A, B. The task is to implement the Half Adder circuit and Print output i.e
sum and carry of two inputs.
Half Adder: A half adder is a type of adder, an electronic circuit that performs the addition of numbers. The
half adder is able to add two single binary digits and provide the output plus a carrying value. It has two
inputs, called A and B, and two outputs S (sum) and C (carry).
Examples:
Input : 0 1
Output: Sum=1, Carry=0
Explanation: According to logical expression Sum=A XOR B i.e 0 XOR 1 =1 , Carry=A AND B i.e 0 AND 1 =0
Input : 1 1
Output: Sum=0, Carry=1
Explanation: According to logical expression Sum=A XOR B i.e 1 XOR 1 =0 , Carry=A AND B i.e 1 AND 1 =1
Approach:
• We take two inputs A and B.
• XOR operation on A and B gives the value of the sum.
• AND operation on A and B gives the value of Carry.
import numpy as np def half_adder(A, B):
# Driver code
A=0
B=1
Sum, Carry = half_adder(A, B) print("Sum:", Sum)
print("Carry:", Carry)
Output:
46
Sum: 1
Carry: 0
Logical Expression :
SUM = C-IN XOR ( A XOR B ) C-0UT= A B + B
C-IN + A C-IN Truth Table :
Examples :
Input : 0 1 1
Output: Sum=0, C-Out=1
According to logical expression Sum= C-IN XOR (A XOR B )i.e 1 XOR (0 XOR 1) =0 , C-Out= A B + B C-IN + A C-
IN i.e., 0 AND 1 + 1 AND 1 + 0 AND 1 = 1
Input : 1 0 0
Output: Sum=1, C-Out=0 Approach :
• We take three inputs A ,B and C-in .
• Applying C-IN XOR (A XOR B ) gives the value of sum
• Applying A B + B C-IN + A C-IN gives the value of C-Out
# python program to implement full adder
# Function to print sum and C-Out def getResult(A, B, C):
47
# Calculating value of sum
Sum = C ^ (A ^ B)
C
# Calculating value of C-Out
C_Out = Bin&(not(A ^ B))| not(A)&B
A=0
B=0
C=1
# passing three inputs of fulladder as arguments to get result function getResult(A, B, C)
ParallelAdder –
A single full adder performs the addition of two one bit numbers and an input carry. But a Parallel Adder is
a digital circuit capable of finding the arithmetic sum of two binary numbers that is greater than one bit in
length by operating on corresponding pairs of bits in parallel. It consists of full adders connected in a chain
where the output carry from each full adder is connected to the carry input of the next higher order full adder
in the chain. A n bit parallel adder requires n full adders to perform the operation.So for the two-bit
number, two adders are needed while for four bit number, four adders are needed and so on. Parallel adders
normally incorporate carry lookahead logic to ensure that carry propagation between subsequent stages of
addition does not limit addition speed.
48
1. As shown in the figure, firstly the full adder FA1 adds A1 and B1 along with the carry C1 to generate the
sum S1 (the first bit of the output sum) and the carry C2 which is connected to the next adder in chain.
2. Next, the full adder FA2 uses this carry bit C2 to add with the input bits A2 and B2 to generate the sum
S2(the second bit of the output sum) and the carry C3 which is again further connected to the next adder
in chain and so on.
3. The process continues till the last full adder FAn uses the carry bit Cn to add with its input An and Bn to
generate the last bit of the output along last carry bit Cout.
5. Write a GUI program to create a window wizard having two text labels, two text fields and two buttons as
Submit and Reset.
window=Tk() window.geometry('250x100')
lbl1=Label(window,text="User Name")
lbl2=Label(window,text="Password") lbl1.grid()
lbl2.grid()
txt1=Entry(window,width=10) txt2=Entry(window,width=10)
txt1.grid(column=1,row=0) txt2.grid(column=1,row=1)
btn1=Button(window,text='Submit') btn2=Button(window,text='Reset')
btn1.grid(column=1,row=3) btn2.grid(column=2,row=3)
window.mainloop()
Output
49