0% found this document useful (0 votes)
1 views28 pages

Selected Python Questions-1

The document contains a collection of Python programming questions (3-23, 28-34) with corresponding code and sample outputs, excluding specific questions. Each question addresses different programming concepts such as calculating compound interest, handling user input, and performing operations on data structures. Additionally, it includes tasks like validating phone numbers and emails, matrix multiplication, and exception handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views28 pages

Selected Python Questions-1

The document contains a collection of Python programming questions (3-23, 28-34) with corresponding code and sample outputs, excluding specific questions. Each question addresses different programming concepts such as calculating compound interest, handling user input, and performing operations on data structures. Additionally, it includes tasks like validating phone numbers and emails, matrix multiplication, and exception handling.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programs: Selected Questions

Questions 3-23 and 28-34 with code and sample outputs

Each question is shown separately with input-based code and its sample output. Excluded questions: 24, 25, 26, 27,
35 and 36. Question 20 in the source list was incomplete, so it has been interpreted as define a matrix and print it.

Question 3: Compound Interest


Write a program to calculate compound interest when principal, rate and number of periods are given.

Code
principal = float(input("Enter principal: "))
rate = float(input("Enter annual rate (%): "))
periods = int(input("Enter number of periods: "))

amount = principal * (1 + rate / 100) ** periods


compound_interest = amount - principal

print("Amount =", round(amount, 2))


print("Compound Interest =", round(compound_interest, 2))

Sample Output
Sample Output
Enter principal: 10000
Enter annual rate (%): 5
Enter number of periods: 2
Amount = 11025.0
Compound Interest = 1025.0

Page 1
Question 4: Person Details
Read the name, address, email and phone number of a person through the keyboard and print the details.

Code
name = input("Enter name: ")
address = input("Enter address: ")
email = input("Enter email: ")
phone = input("Enter phone number: ")

print("\nPerson Details")
print("Name :", name)
print("Address:", address)
print("Email :", email)
print("Phone :", phone)

Sample Output
Sample Output
Enter name: Ananya
Enter address: Chennai
Enter email: ananya@[Link]
Enter phone number: 9876543210

Person Details
Name : Ananya
Address: Chennai
Email : ananya@[Link]
Phone : 9876543210

Page 2
Question 5: Triangle Pattern
Print the given triangle using a for loop.

Code
rows = int(input("Enter number of rows: "))

for i in range(rows, 0, -1):


for _ in range(rows - i + 1):
print(i, end=" ")
print()

Sample Output
Sample Output
Enter number of rows: 5
5
4 4
3 3 3
2 2 2 2
1 1 1 1 1

Page 3
Question 6: Character Type Check
Check whether the given input is a digit, lowercase character, uppercase character or a special character using an
if-elif ladder.

Code
ch = input("Enter a character: ")

if len(ch) != 1:
print("Please enter only one character.")
elif '0' <= ch <= '9':
print("Digit")
elif 'a' <= ch <= 'z':
print("Lowercase character")
elif 'A' <= ch <= 'Z':
print("Uppercase character")
else:
print("Special character")

Sample Output
Sample Output
Enter a character: @
Special character

Page 4
Question 7: Prime Numbers in an Interval
Print all prime numbers in a given interval using break.

Code
start = int(input("Enter start value: "))
end = int(input("Enter end value: "))

print("Prime numbers are:")


for num in range(start, end + 1):
if num < 2:
continue
is_prime = True
divisor = 2
while divisor * divisor <= num:
if num % divisor == 0:
is_prime = False
break
divisor += 1
if is_prime:
print(num, end=" ")

Sample Output
Sample Output
Enter start value: 10
Enter end value: 30
Prime numbers are:
11 13 17 19 23 29

Page 5
Question 8: List and Tuple to Arrays
Convert a list and a tuple into arrays.

Code
import numpy as np

list_input = input("Enter list elements separated by space: ")


tuple_input = input("Enter tuple elements separated by space: ")

my_list = [int(x) for x in list_input.split()]


my_tuple = tuple(int(x) for x in tuple_input.split())

list_array = [Link](my_list)
tuple_array = [Link](my_tuple)

print("List to array :", list_array)


print("Tuple to array:", tuple_array)

Sample Output
Sample Output
Enter list elements separated by space: 1 2 3 4
Enter tuple elements separated by space: 5 6 7 8
List to array : [1 2 3 4]
Tuple to array: [5 6 7 8]

Page 6
Question 9: Common Values Between Arrays
Find common values between two arrays.

Code
import numpy as np

arr1 = [Link]([int(x) for x in input("Enter first array elements: ").split()])


arr2 = [Link]([int(x) for x in input("Enter second array elements: ").split()])

common = np.intersect1d(arr1, arr2)


print("Common values:", common)

Sample Output
Sample Output
Enter first array elements: 1 2 3 4 5
Enter second array elements: 3 4 5 6 7
Common values: [3 4 5]

Page 7
Question 10: Palindrome Function
Write a function called palindrome that takes a string and returns True if it is a palindrome and False otherwise.

Code
def palindrome(text):
left = 0
right = len(text) - 1

while left < right:


if text[left] != text[right]:
return False
left += 1
right -= 1
return True

word = input("Enter a word: ")


print(palindrome(word))

Sample Output
Sample Output
Enter a word: madam
True

Page 8
Question 11: Check Sorted List
Write a function called is_sorted that returns True if the list is sorted in ascending order and False otherwise.

Code
def is_sorted(items):
for i in range(len(items) - 1):
if items[i] > items[i + 1]:
return False
return True

numbers = [int(x) for x in input("Enter list elements: ").split()]


print(is_sorted(numbers))

Sample Output
Sample Output
Enter list elements: 1 2 4 5
True

Page 9
Question 12: Check Duplicates
Write a function called has_duplicates that returns True if any element appears more than once.

Code
def has_duplicates(items):
seen = set()
for item in items:
if item in seen:
return True
[Link](item)
return False

values = input("Enter list elements separated by space: ").split()


print(has_duplicates(values))

Sample Output
Sample Output
Enter list elements separated by space: 10 20 30 20
True

Page 10
Question 13: Remove Duplicates
Write a function called remove_duplicates that returns a new list with only unique elements.

Code
def remove_duplicates(items):
return list(set(items))

values = input("Enter list elements separated by space: ").split()


print(remove_duplicates(values))

Sample Output
Sample Output
Enter list elements separated by space: 1 2 2 3 4 4 5
['1', '2', '3', '4', '5']

Page 11
Question 14: Add Missing Single-Letter Words
The given [Link] does not contain single-letter words. Add 'I', 'a', and the empty string to the word list.

Code
filename = input("Enter file name: ")

with open(filename, "r") as file:


words = [[Link]() for line in file]

extra_words = ["I", "a", ""]


updated_words = extra_words + words

print("First 10 entries from updated list:")


for word in updated_words[:10]:
print(repr(word))

Sample Output
Sample Output
Enter file name: [Link]
First 10 entries from updated list:
'I'
'a'
''
'ability'
'able'
'about'
'above'
'accept'
'account'
'across'

Page 12
Question 15: Invert Dictionary
Read dictionary values from the user and invert the dictionary so keys become values and values become keys.

Code
def invert_dict(data):
inverted = {}
for key, value in [Link]():
inverted[value] = key
return inverted

n = int(input("Enter number of items: "))


data = {}
for _ in range(n):
key = input("Enter key: ")
value = input("Enter value: ")
data[key] = value

print("Original dictionary:", data)


print("Inverted dictionary:", invert_dict(data))

Sample Output
Sample Output
Enter number of items: 2
Enter key: a
Enter value: 1
Enter key: b
Enter value: 2
Original dictionary: {'a': '1', 'b': '2'}
Inverted dictionary: {'1': 'a', '2': 'b'}

Page 13
Question 16: Add Commas Between Characters
Add a comma between the characters of a word. Example: Apple becomes A,p,p,l,e.

Code
word = input("Enter a word: ")
result = ",".join(word)
print(result)

Sample Output
Sample Output
Enter a word: Apple
A,p,p,l,e

Page 14
Question 17: Remove a Word from a String
Remove the given word in all places in a string.

Code
sentence = input("Enter a sentence: ")
word = input("Enter the word to remove: ")

result = [Link](word, "")


result = " ".join([Link]())
print(result)

Sample Output
Sample Output
Enter a sentence: this is a test and this is simple
Enter the word to remove: is
th a test and th simple

Page 15
Question 18: Capitalize Each Word Without Built-in Title Function
Replace the first letter of every word with uppercase and the rest with lowercase without using a built-in function.

Code
def custom_title(sentence):
words = [Link]()
result = []

for word in words:


new_word = ""
for i, ch in enumerate(word):
if 'a' <= ch <= 'z' and i == 0:
new_word += chr(ord(ch) - 32)
elif 'A' <= ch <= 'Z' and i > 0:
new_word += chr(ord(ch) + 32)
else:
new_word += ch
[Link](new_word)
return " ".join(result)

text = input("Enter a sentence: ")


print(custom_title(text))

Sample Output
Sample Output
Enter a sentence: pYTHon proGRAMMING is fun
Python Programming Is Fun

Page 16
Question 19: Recursive Binary Strings
Write a recursive function that generates all binary strings of n-bit length.

Code
def generate_binary(n, current=""):
if len(current) == n:
print(current)
return
generate_binary(n, current + "0")
generate_binary(n, current + "1")

n = int(input("Enter n: "))
generate_binary(n)

Sample Output
Sample Output
Enter n: 3
000
001
010
011
100
101
110
111

Page 17
Question 20: Define and Print a Matrix
Write a Python program that defines a matrix and prints it. (The original prompt is incomplete, so this version prints
the matrix row by row.)

Code
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))

matrix = []
for i in range(rows):
row = [int(x) for x in input(f"Enter elements of row {i + 1}: ").split()]
[Link](row[:cols])

print("Matrix is:")
for row in matrix:
print(row)

Sample Output
Sample Output
Enter number of rows: 3
Enter number of columns: 3
Enter elements of row 1: 1 2 3
Enter elements of row 2: 4 5 6
Enter elements of row 3: 7 8 9
Matrix is:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

Page 18
Question 21: Square Matrix Multiplication
Write a Python program to perform multiplication of two square matrices.

Code
size = int(input("Enter order of square matrices: "))

print("Enter elements of first matrix:")


A = []
for i in range(size):
row = [int(x) for x in input(f"Row {i + 1}: ").split()]
[Link](row[:size])

print("Enter elements of second matrix:")


B = []
for i in range(size):
row = [int(x) for x in input(f"Row {i + 1}: ").split()]
[Link](row[:size])

result = [[0 for _ in range(size)] for _ in range(size)]

for i in range(size):
for j in range(size):
for k in range(size):
result[i][j] += A[i][k] * B[k][j]

print("Product matrix:")
for row in result:
print(row)

Sample Output
Sample Output
Enter order of square matrices: 2
Enter elements of first matrix:
Row 1: 1 2
Row 2: 3 4
Enter elements of second matrix:
Row 1: 5 6
Row 2: 7 8
Product matrix:
[19, 22]
[43, 50]

Page 19
Question 22: Create a Module
Show how to make a module using different geometrical shapes and operations on them as functions.

Code
# [Link]
import math

def area_circle(radius):
return [Link] * radius * radius

def area_rectangle(length, breadth):


return length * breadth

def area_triangle(base, height):


return 0.5 * base * height

# [Link]
import shapes

radius = float(input("Enter radius of circle: "))


length = float(input("Enter length of rectangle: "))
breadth = float(input("Enter breadth of rectangle: "))
base = float(input("Enter base of triangle: "))
height = float(input("Enter height of triangle: "))

print("Circle area =", round(shapes.area_circle(radius), 2))


print("Rectangle area =", shapes.area_rectangle(length, breadth))
print("Triangle area =", shapes.area_triangle(base, height))

Sample Output
Sample Output
Enter radius of circle: 3
Enter length of rectangle: 4
Enter breadth of rectangle: 5
Enter base of triangle: 6
Enter height of triangle: 2
Circle area = 28.27
Rectangle area = 20.0
Triangle area = 6.0

Page 20
Question 23: General Exception Handling
Use the structure of exception handling for general-purpose exceptions.

Code
try:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Result =", a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter only numbers.")
except Exception as error:
print("An unexpected error occurred:", error)
finally:
print("Program completed.")

Sample Output
Sample Output
Enter first number: 10
Enter second number: 0
Cannot divide by zero.
Program completed.

Page 21
Question 28: Validate Phone Number and Email
Read a phone number and email-id from the user and validate them for correctness.

Code
import re

phone = input("Enter phone number: ")


email = input("Enter email: ")

phone_ok = bool([Link](r"[6-9]\d{9}", phone))


email_ok = bool([Link](r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}", email))

print("Valid phone number" if phone_ok else "Invalid phone number")


print("Valid email" if email_ok else "Invalid email")

Sample Output
Sample Output
Enter phone number: 9876543210
Enter email: student1@[Link]
Valid phone number
Valid email

Page 22
Question 29: Merge Two Files into a Third File
Merge two given file contents into a third file.

Code
file1 = input("Enter first file name: ")
file2 = input("Enter second file name: ")
file3 = input("Enter output file name: ")

with open(file1, "r") as f1, open(file2, "r") as f2, open(file3, "w") as f3:
[Link]([Link]())
[Link]("\n")
[Link]([Link]())

print("Contents merged into", file3)

Sample Output
Sample Output
Enter first file name: [Link]
Enter second file name: [Link]
Enter output file name: [Link]
Contents merged into [Link]

Page 23
Question 30: Check Whether a Word Exists in a File
Open a given file and check whether a given word is present in it.

Code
def find_word(filename, target):
with open(filename, "r") as file:
content = [Link]()
if target in content:
print("Word found")
else:
print("Word not found")

filename = input("Enter file name: ")


target = input("Enter word to search: ")
find_word(filename, target)

Sample Output
Sample Output
Enter file name: [Link]
Enter word to search: Python
Word found

Page 24
Question 31: Most Frequent Word in a File
Read text from a file and find the word with the highest number of occurrences.

Code
filename = input("Enter file name: ")

with open(filename, "r") as file:


words = [Link]().lower().split()

frequency = {}
for word in words:
frequency[word] = [Link](word, 0) + 1

most_word = max(frequency, key=[Link])


print("Most frequent word:", most_word)
print("Count:", frequency[most_word])

Sample Output
Sample Output
Enter file name: [Link]
Most frequent word: python
Count: 4

Page 25
Question 32: Count Words, Vowels and Letters in a File
Read file1 and display the number of words, vowels, blank spaces, lowercase letters and uppercase letters.

Code
def analyze_file(filename):
with open(filename, "r") as file:
content = [Link]()

words = len([Link]())
vowels = sum(1 for ch in content if [Link]() in "aeiou")
blanks = [Link](" ")
lower = sum(1 for ch in content if [Link]())
upper = sum(1 for ch in content if [Link]())

print("Words :", words)


print("Vowels :", vowels)
print("Blank spaces :", blanks)
print("Lowercase letters:", lower)
print("Uppercase letters:", upper)

filename = input("Enter file name: ")


analyze_file(filename)

Sample Output
Sample Output
Enter file name: [Link]
Words : 6
Vowels : 8
Blank spaces : 5
Lowercase letters: 17
Uppercase letters: 2

Page 26
Question 33: Explore NumPy, Matplotlib and SciPy
Import numpy, [Link] and scipy and explore their functionalities.

Code
import numpy as np
import [Link] as plt
import scipy

arr = [Link]([int(x) for x in input("Enter array elements: ").split()])


print("NumPy array:", arr)
print("Mean:", [Link](arr))

x = [int(x) for x in input("Enter x values for plot: ").split()]


y = [int(y) for y in input("Enter y values for plot: ").split()]
[Link](x, y)
[Link]("Simple Line Plot")
[Link]("[Link]")
print("Plot saved as [Link]")

print("SciPy version:", scipy.__version__)

Sample Output
Sample Output
Enter array elements: 1 2 3 4
NumPy array: [1 2 3 4]
Mean: 2.5
Enter x values for plot: 1 2 3
Enter y values for plot: 2 4 6
Plot saved as [Link]
SciPy version: 1.x.x

Page 27
Question 34: Install NumPy with pip and Explore It
Install the NumPy package with pip and explore it.

Code
# Command to install
pip install numpy

# Python code to explore NumPy


import numpy as np

start = int(input("Enter start value: "))


end = int(input("Enter end value: "))

arr = [Link](start, end + 1)


print("Array:", arr)
print("Squares:", arr ** 2)
print("Sum:", [Link](arr))

Sample Output
Sample Output
Enter start value: 1
Enter end value: 5
Array: [1 2 3 4 5]
Squares: [ 1 4 9 16 25]
Sum: 15

Page 28

You might also like