1.
How to Get Started with Python and Execute First Program in Python
Steps:
1. Visit the Python website.
2. Download the latest version of Python and install it.
3. Open the terminal or command prompt, type python to enter the Python
interpreter.
4. Type the following code to execute your first program:
print("Hello, World!")
Output:
Hello, World!
2. Start the Python Interpreter and Type help() to Start the Online Help Utility
Code:
help()
Output:
This will open the help utility, providing interactive help and documentation
about Python modules, functions, and objects.
3. Start a Python Interpreter and Use it as a Calculator
Code:
>>> 5 + 3
>>> 6 * 7
42
>>> 9 / 3
3.0
>>> 2 ** 3
Output: 8, 42, 3.0, 8
4. Write a Program to Print Each Line of a File in Reverse Order
Code:
filename = "example.txt"
with open(filename, 'r') as file:
lines = file.readlines()
for line in reversed(lines):
print(line.strip())
Output:
If the file contains:
Hello
World
Python
Python
World
5. Write a Program to Purposefully Raise Indentation Error and Correct It
Code (with error):
if True:
print("This will raise an error")
Output:
IndentationError: expected an indented block
Corrected Code:
if True:
print("This will work fine")
Output: This will work fine
6. Write a Program to Implement Half Adder, Full Adder, and Parallel Adder
Code:
def half_adder(a, b):
return a ^ b, a & b
def full_adder(a, b, c):
return a ^ b ^ c, (a & b) | (b & c) | (c & a)
def parallel_adder(bits1, bits2):
carry = 0
result = []
for i in range(len(bits1) - 1, -1, -1):
sum_, carry = full_adder(bits1[i], bits2[i], carry)
result.insert(0, sum_)
result.insert(0, carry).
return result.
print(half_adder(1, 0))
print(full_adder(1, 1, 0))
print(parallel_adder([1, 0, 1], [1, 1, 0]))
Output:
(1, 0)
(0, 1)
[1, 0, 0, 1]
7. Write a Program to Calculate Compound Interest When Principal, Rate, and
Number of Periods Are Given
Code:
P = float(input("Enter principal: "))
R = float(input("Enter rate: "))
T = int(input("Enter time in years: "))
A = P * (1 + R/100)**T
CI = A - P
print("Compound Interest:", CI)
Output:
Enter principal: 1000
Enter rate: 5
Enter time in years: 2
Compound Interest: 102.5
8. Given Coordinates (x1, y1), (x2, y2) Find the Distance Between Two Points
Code:
import math
x1, y1 = 1, 2
x2, y2 = 4, 6
distance = math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
print("Distance:", distance)
Output:
Distance: 5.0
9. Read Name, Address, Email, and Phone Number of a Person Through
Keyboard and Print the Details
Code:
name = input("Enter name: ")
address = input("Enter address: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")
print(f"Name: {name}")
print(f"Address: {address}")
print(f"Email: {email}")
print(f"Phone: {phone}")
Output:
Enter name: John Doe
Enter address: 123 Street
Enter phone number: 1234567890
Name: John Doe
Address: 123 Street
Email: [email protected]
Phone: 1234567890
10. Write a Program to Implement Digital Logic Gates – AND, OR, NOT, EX-OR
Code:
def AND(a, b):
return a & b
def OR(a, b):
return a | b
def NOT(a):
return ~a
def XOR(a, b):
return a ^ b
print(AND(1, 0))
print(OR(1, 0))
print(NOT(1))
print(XOR(1, 0))
Output: 0, 1, - 2, 1
11. Print the Below Triangle Using For Loop
Code:
for i in range(5, 0, -1):
print(f"{i} " * i)
Output:
44
333
2222
11111
12. Write a Python Code to Merge Two Given File Contents into a Third File
Code:
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2,
open('merged.txt', 'w') as merged:
merged.write(file1.read())
merged.write(file2.read())
Output:
The content of file1.txt and file2.txt will be combined and saved in
merged.txt.
13. Write a Program to Check Whether the Given Input is Digit, Lowercase
Character, Uppercase Character, or a Special Character
Code:
ch = input("Enter a character: ")
if ch.isdigit():
print("Digit")
elif ch.islower():
print("Lowercase character")
elif ch.isupper():
print("Uppercase character")
else:
print("Special character")
Output:
Enter a character: a
Lowercase character
14. Write a Function that Reads a File file1 and Displays the Number of
Words, Number of Vowels, Blank Spaces, Lowercase Letters, and Uppercase
Letters
Code:
def file_analysis(filename):
with open(filename, 'r') as file:
content = file.read()
words = content.split()
vowels = sum(1 for c in content if c in 'aeiouAEIOU')
spaces = content.count(' ')
lowercase = sum(1 for c in content if c.islower())
uppercase = sum(1 for c in content if c.isupper())
print(f"Words: {len(words)}")
print(f"Vowels: {vowels}")
print(f"Spaces: {spaces}")
print(f"Lowercase letters: {lowercase}")
print(f"Uppercase letters: {uppercase}")
file_analysis('example.txt')
Output:
Words: 5
Vowels: 7
Spaces: 4
Lowercase letters: 15
Uppercase letters: 3
Here are the Python programs without the extra "Question" part:
15. Python Program to Print the Fibonacci sequence using while loop
n = int(input())
a, b = 0, 1
while a < n:
print(a, end=" ")
a, b = b, a + b
Output:
10
0112358
16. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
a = int(input())
b = int(input())
print("AND:", a & b)
print("OR:", a | b)
print("NOT:", ~a)
print("EX-OR:", a ^ b)
Output:
AND: 0
OR: 1
NOT: -2
EX-OR: 1
17. Python program to print all prime numbers in a given interval (use break)
start = 10
end = 20
for num in range(start, end + 1):
for i in range(2, num):
if num % i == 0:
break
else:
print(num, end=" ")
Output:
11 13 17 19
18. Write a program to implement Half Adder, Full Adder, and Parallel Adder
def half_adder(a, b):
sum = a ^ b
carry = a & b
return sum, carry
def full_adder(a, b, carry_in):
sum = a ^ b ^ carry_in
carry_out = (a & b) | (carry_in & (a ^ b))
return sum, carry_out
Output:
No direct output; function calls required for testing.
19. Write a program to compute LCM of two numbers by taking input from
the user
import math
a = int(input())
b = int(input())
lcm = (a * b) // math.gcd(a, b)
print("LCM:", lcm)
Output:
5
LCM: 20
20. Write a GUI program to create a window wizard having two text labels,
two text fields, and two buttons as Submit and Reset
import tkinter as tk
window = tk.Tk()
window.title("Window Wizard")
label1 = tk.Label(window, text="Name:")
label1.grid(row=0, column=0)
label2 = tk.Label(window, text="Age:")
label2.grid(row=1, column=0)
entry1 = tk.Entry(window)
entry1.grid(row=0, column=1)
entry2 = tk.Entry(window)
entry2.grid(row=1, column=1)
submit_button = tk.Button(window, text="Submit")
submit_button.grid(row=2, column=0)
reset_button = tk.Button(window, text="Reset")
reset_button.grid(row=2, column=1)
window.mainloop()
Output:
A GUI window with labels, text fields, and buttons.
21. Write a program add.py that takes 2 numbers as command line
arguments and prints its sum
import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
print(num1 + num2)
Output:
$ python add.py 3 5
22. Import SciPy and explore their functionalities
import scipy
from scipy import stats
print(scipy.__version__)
print(stats.norm.cdf(0))
Output:
1.9.3
0.5
23. Write a program to convert a list and tuple into arrays
import numpy as np
lst = [1, 2, 3, 4]
tup = (5, 6, 7, 8)
array_from_list = np.array(lst)
array_from_tuple = np.array(tup)
print(array_from_list)
print(array_from_tuple)
Output:
[1 2 3 4]
[5 6 7 8]
24. Write a program to find common values between two arrays
import numpy as np
array1 = np.array([1, 2, 3, 4])
array2 = np.array([3, 4, 5, 6])
common_values = np.intersect1d(array1, array2)
print(common_values)
Output:
[3 4]
25. Write a function called gcd that takes parameters a and b and returns
their greatest common divisor
import math
def gcd(a, b):
return math.gcd(a, b)
print(gcd(12, 15))
Output:
26. Import SciPy and explore their functionalities
import scipy
from scipy import linalg
print(scipy.__version__)
print(linalg.det([[1, 2], [3, 4]]))
Output:
1.9.3
-2.0
27. Write a function called palindrome that takes a string argument and
returns True if it is a palindrome and False otherwise
def palindrome(string):
return string == string[::-1]
print(palindrome("madam"))
print(palindrome("hello"))
Output:
True
False
28. Write a program to implement Digital Logic Gates – AND, OR, NOT, EX-OR
a = int(input())
b = int(input())
print("AND:", a & b)
print("OR:", a | b)
print("NOT:", ~a)
print("EX-OR:", a ^ b)
Output:
AND: 0
OR: 1
NOT: -2
EX-OR: 1
29. Find mean, median, mode for the given set of numbers in a list
import statistics
numbers = [1, 2, 2, 3, 4]
print("Mean:", statistics.mean(numbers))
print("Median:", statistics.median(numbers))
print("Mode:", statistics.mode(numbers))
Output:
Mean: 2.4
Median: 2
Mode: 2
30. Write a program for Creating a Pandas Series and Basic Operations on
Series
import pandas as pd
data = [1, 2, 3, 4]
series = pd.Series(data)
print(series)
print(series.mean())
Output:
0 1
1 2
2 3
3 4
dtype: int64
2.5
31. Write a Python program to create a tuple
t = (1, 2, 3, 4)
print(t)
Output:
(1, 2, 3, 4)
32. Write a Python program to construct a Data Frame and explore Basic
Operations on DataFrame
import pandas as pd
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [24, 27, 22]}
df = pd.DataFrame(data)
print(df)
Output:
Name Age
0 Alice 24
1 Bob 27
2 Charlie 22
33. Write a Python program to create a tuple with different data types
t = (1, "hello", 3.14, True)
print(t)
Output:
(1, 'hello', 3.14, True)
34. Import Pandas and Plotly and explore their functionalities
import pandas as pd
import plotly.express as px
data = {'x': [1, 2, 3], 'y': [4, 5, 6]}
df = pd.DataFrame(data)
fig = px.scatter(df, x='x', y='y')
fig.show()
Output:
A scatter plot will be displayed in a new window.
Here are the Python programs for the tasks you've mentioned:
35. Write a Python program to check whether an element exists within a
tuple
t = (1, 2, 3, 4)
element = 3
print(element in t)
Output:
True
36. Write a program for sorting
lst = [4, 1, 3, 2]
lst.sort()
print(lst)
Output:
[1, 2, 3, 4]
37. 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
def is_sorted(lst):
return lst == sorted(lst)
print(is_sorted([1, 2, 3, 4]))
print(is_sorted([4, 3, 2, 1]))
Output:
True
False
38 . Write a program for Math operations on array using numpy
import numpy as np
arr = np.array([1, 2, 3, 4])
print("Add 2:", arr + 2)
print("Multiply by 2:", arr * 2)
print("Square:", np.square(arr))
Output:
Add 2: [3 4 5 6]
Multiply by 2: [2 4 6 8]
Square: [1 4 9 16]
39. 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.
def has_duplicates(lst):
return len(lst) != len(set(lst))
print(has_duplicates([1, 2, 3, 4]))
print(has_duplicates([1, 2, 2, 4]))
Output:
False
True
i) Write a function called remove_duplicates that takes a list and returns a
new list with only the unique elements from the original.
def remove_duplicates(lst):
return list(set(lst))
print(remove_duplicates([1, 2, 3, 2, 4]))
Output:
[1, 2, 3, 4]
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.
words = ["apple", "banana", "cherry"]
words.extend(["I", "a", ""])
print(words)
Output:
['apple', 'banana', 'cherry', 'I', 'a', '']
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.
def invert_dict(d):
return {v: k for k, v in d.items()}
d = {'a': 1, 'b': 2, 'c': 3}
print(invert_dict(d))
Output:
{1: 'a', 2: 'b', 3: 'c'}
40. i) Add a comma between the characters. If the given word is 'Apple', it
should become 'A,p,p,l,e'
word = "Apple"
print(",".join(word))
Output:
A,p,p,l,e
ii) Remove the given word in all the places in a string
string = "Hello world, Hello again"
word = "Hello"
print(string.replace(word, ""))
Output:
world, again
iii) Write a function that takes a sentence as an input parameter and replaces
the first letter of every word with the corresponding uppercase letter and the
rest of the letters in the word by corresponding letters in lowercase without
using a built-in function
def capitalize_sentence(sentence):
words = sentence.split()
result = []
for word in words:
result.append(word[0].upper() + word[1:].lower())
return " ".join(result)
print(capitalize_sentence("hello world"))
Output:
Hello World
41. Writes a recursive function that generates all binary strings of n-bit
length
def generate_binary_strings(n, s=""):
if len(s) == n:
print(s)
return
generate_binary_strings(n, s + "0")
generate_binary_strings(n, s + "1")
generate_binary_strings(3)
Output:
000
001
010
011
100
101
110
111
42. Write a program for searching
lst = [10, 20, 30, 40, 50]
target = 30
if target in lst:
print(f"{target} found in list")
else:
print(f"{target} not found")
Output: 30 found in list
43. Write a Python program to implement all set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print("Union:", set1 | set2)
print("Intersection:", set1 & set2)
print("Difference:", set1 - set2)
print("Symmetric Difference:", set1 ^ set2)
Output:
Union: {1, 2, 3, 4, 5, 6}
Intersection: {3, 4}
Difference: {1, 2}
Symmetric Difference: {1, 2, 5, 6}
44. Write a program for slicing arrays using numpy
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr[1:4])
Output:
[2 3 4]
45. Write a program to check whether a string is palindrome or not
def is_palindrome(s):
return s == s[::-1]
print(is_palindrome("madam"))
print(is_palindrome("hello"))
Output:
True
False
46. Import numpy, and explore their functionalities
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr + 2)
print(np.mean(arr))
print(np.dot(arr, arr))
Output:
[3 4 5 6]
2.5
30
Here is the Python code along with the corresponding questions:
47. i) Write a Python program that defines a matrix and prints it.
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
print(row)
Output:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
47. ii) Write a Python program to perform addition of two square matrices.
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
result = [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in
range(len(matrix1))]
for row in result:
print(row)
Output:
[6, 8]
[10, 12]
47. iii) Write a Python program to perform multiplication of two square
matrices.
matrix1 = [[1, 2], [3, 4]]
matrix2 = [[5, 6], [7, 8]]
result = [[sum(a * b for a, b in zip(matrix1_row, matrix2_col)) for matrix2_col
in zip(*matrix2)] for matrix1_row in matrix1]
for row in result:
print(row)
Output:
[19, 22]
48. Simple Calculator program by making use of functions.
def add(a, b): return a + b
def subtract(a, b): return a - b
def multiply(a, b): return a * b
def divide(a, b): return a / b
print(add(5, 3))
print(subtract(5, 3))
print(multiply(5, 3))
print(divide(5, 3))
Output:
15
1.6666666666666667
49. Write a program to print each line of a file in reverse order.
with open('sample.txt', 'r') as file:
lines = file.readlines()
for line in reversed(lines):
print(line.strip())
50. Find the factorial of a number using recursion.
def factorial(n): return 1 if n == 0 else n * factorial(n - 1)
print(factorial(5))
Output:
120
51. Install NumPy package with pip and explore it.
pip install numpy
After installing, you can explore it by running:
import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr)
Output:
[1 2 3 4]
52. Write a function cumulative_product to compute cumulative product of a
list of numbers.
import numpy as np
def cumulative_product(lst): return np.cumprod(lst)
print(cumulative_product([1, 2, 3, 4]))
Output:
[ 1 2 6 24]
53. 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 file_analysis(filename):
with open(filename, 'r') as file:
text = file.read()
words = text.split()
vowels = sum(1 for char in text if char in 'aeiouAEIOU')
spaces = text.count(' ')
lowercase = sum(1 for char in text if char.islower())
uppercase = sum(1 for char in text if char.isupper())
print(f"Words: {len(words)} Vowels: {vowels} Spaces: {spaces}
Lowercase: {lowercase} Uppercase: {uppercase}")
54. Write a function reverse to print the given list in the reverse order.
def reverse(lst): print(lst[::-1])
reverse([1, 2, 3, 4])
Output:
[4, 3, 2, 1]
55. Write a Python code to read text from a text file, find the word with most
number of occurrences.
from collections import Counter
def most_frequent_word(filename):
with open(filename, 'r') as file:
words = file.read().split()
most_common = Counter(words).most_common(1)
print(f"Most frequent word: {most_common[0][0]} with {most_common[0]
[1]} occurrences.")
56. Write a program that detects an Exception.
try:
x=1/0
except Exception as e:
print(f"Exception occurred: {e}")
Output:
Exception occurred: division by zero
57. 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.
Create a module geometry.py:
def area_of_circle(radius): return 3.14 * radius ** 2
def area_of_rectangle(length, width): return length * width
In the main script:
import geometry
print(geometry.area_of_circle(5))
print(geometry.area_of_rectangle(4, 6))
Output:
78.5
24
58. Write a program that raises an Exception (divide by zero error, voter’s
age validity).
try:
x=1/0
except ZeroDivisionError:
print("Cannot divide by zero!")
Output:
Cannot divide by zero!
59. Write a Python program to demonstrate the usage of Method Resolution
Order (MRO) in multiple levels of Inheritance.
class A:
def method(self): print("A method")
class B(A):
def method(self): print("B method")
class C(B):
pass
C().method()
Output:
B method
60. Write a program that raises an Exception as string(), student mark range
validation.
def validate_marks(marks):
if marks < 0 or marks > 100:
raise ValueError("Marks must be between 0 and 100.")
try:
validate_marks(150)
except ValueError as e:
print(e)
Output:
Marks must be between 0 and 100.
61. Write a Python code to merge two given file contents into a third file.
data1 = open('file1.txt').read()
data2 = open('file2.txt').read()
open('merged_file.txt', 'w').write(data1 + "\n" + data2)
print(open('merged_file.txt').read())
Example Input Files:
file1.txt:
Hello from File 1
file2.txt:
Hello from File 2
Example Output (contents of merged_file.txt):
Hello from File 1
Hello from File 2
62. Use the structure of exception handling for all general purpose
exceptions.
try:
x=1/0
except ZeroDivisionError:
print("ZeroDivisionError caught.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
ZeroDivisionError caught.
63. Write a Python code to merge two given file contents into a third file.
data1 = open('file1.txt').read()
data2 = open('file2.txt').read()
open('merged_file.txt', 'w').write(data1 + "\n" + data2)
print(open('merged_file.txt').read())
Example Input Files:
file1.txt:
Hello from File 1
file2.txt:
Hello from File 2
Example Output (contents of merged_file.txt):
Hello from File 1
Hello from File 2
64. Write a Python code to read a phone number and email-id from the user
and validate it for correctness.
Code:
import re
def validate_phone(phone):
pattern = r"^[0-9]{10}$"
return bool(re.match(pattern, phone)r
def validate_email(email):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
return bool(re.match(pattern, email))
phone = input("Enter phone number: ")
email = input("Enter email: ")
print("Phone Valid:", validate_phone(phone))
print("Email Valid:", validate_email(email))
Output:
Enter phone number: 1234567890
Phone Valid: True
Email Valid: True
65. 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.
Code:
def find_words_in_file(filename, words):
with open(filename, 'r') as file:
content = file.read()
for word in words:
if word in content:
print(f"'{word}' found in the file.")
words_to_find = ["Python", "code", "function"]
find_words_in_file('sample.txt', words_to_find)
Output:
If sample.txt contains the words "Python" and "code":
'Python' found in the file.
'code' found in the file.
66. 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.
Code:
from tkinter import *
def draw_rectangle(canvas, rectangle):
canvas.create_rectangle(rectangle[0], rectangle[1], rectangle[2],
rectangle[3])
root = Tk()
canvas = Canvas(root, width=400, height=400)
canvas.pack()
draw_rectangle(canvas, (50, 50, 150, 150))
root.mainloop()
Output:
A window opens with a rectangle drawn on the canvas.
66. 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.
Code:
from tkinter import *
class Rectangle:
def __init__(self, x1, y1, x2, y2, color):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.color = color
def draw_rectangle(canvas, rectangle):
canvas.create_rectangle(rectangle.x1, rectangle.y1, rectangle.x2,
rectangle.y2, fill=rectangle.color)
root = Tk()
canvas = Canvas(root, width=400, height=400)
canvas.pack()
rect = Rectangle(50, 50, 150, 150, 'blue')
draw_rectangle(canvas, rect)
root.mainloop()
Output:
A window opens with a blue rectangle drawn on the canvas.
66. 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.
Code:
from tkinter import *
def draw_point(canvas, point):
canvas.create_oval(point[0] - 2, point[1] - 2, point[0] + 2, point[1] + 2,
fill='red')
root = Tk()
canvas = Canvas(root, width=400, height=400)
canvas.pack()
draw_point(canvas, (100, 100))
root.mainloop()
Output:
A window opens with a red point drawn on the canvas.
66. 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.
Code:
from tkinter import *
class Circle:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
def draw_circle(canvas, circle):
canvas.create_oval(circle.x - circle.radius, circle.y - circle.radius,
circle.x + circle.radius, circle.y + circle.radius, fill=circle.color)
root = Tk()
canvas = Canvas(root, width=400, height=400)
canvas.pack()
circle1 = Circle(100, 100, 50, 'green')
circle2 = Circle(200, 200, 30, 'yellow')
draw_circle(canvas, circle1)
draw_circle(canvas, circle2)
root.mainloop()
Output:
A window opens with two circles drawn on the canvas: one green and one
yellow.