0% found this document useful (0 votes)
2 views11 pages

Python Programming Assignment

The document contains a series of Python programming assignments that cover various tasks such as checking for palindromes, counting words, manipulating strings, and performing operations on lists and tuples. Each assignment includes code snippets and example outputs to demonstrate the expected results. The tasks range from basic string manipulation to more complex list and tuple operations.

Uploaded by

sushantjha0251
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)
2 views11 pages

Python Programming Assignment

The document contains a series of Python programming assignments that cover various tasks such as checking for palindromes, counting words, manipulating strings, and performing operations on lists and tuples. Each assignment includes code snippets and example outputs to demonstrate the expected results. The tasks range from basic string manipulation to more complex list and tuple operations.

Uploaded by

sushantjha0251
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

Programming Assignment
1. WAP to check whether a string is a palindrome or not.
s = input("Enter a string: ")
if s == s[::-1]:
print("It is a palindrome")
else:
print("Not a palindrome")

Output:
Enter a string: racecar
It is a palindrome

​ . WAP that reads a line, counts the words and then displays the number of words in a
2
line.
line = input("Enter a line: ")
words = [Link]()
print("Number of words in the line:", len(words))

Output:
Enter a line: Learning Python is very interesting
Number of words in the line: 5

3. WAP that reads a string and then prints a string that capitalize every other letter in the
string.
s = input("Enter a string: ")
res = ""
for i in range(len(s)):
if i % 2 == 0:
res += s[i].upper()
else:
res += s[i].lower()
print("Processed string:", res)

Output:
Enter a string: computer
Processed string: CoMpUtEr
4. WAP that reads a line, counts the number of times substring ‘is’ appears in the line and
then displays the count.
line = input("Enter a line: ")
count = [Link]().count('is')
print("The substring 'is' appears:", count, "times")

Output:
Enter a line: This is a pencil and this is a pen
The substring 'is' appears: 2 times

5. WAP to remove vowels from a string.


s = input("Enter a string: ")
vowels = "aeiouAEIOU"
res = "".join([char for char in s if char not in vowels])
print("String without vowels:", res)

Output:
Enter a string: Beautiful Day
String without vowels: Btfl Dy

6. WAP that reads a string and displays the occurrence of words starting with a vowel in
the given string.
line = input("Enter a string: ")
words = [Link]()
vowels = "aeiouAEIOU"
print("Words starting with a vowel:")
for w in words:
if w[0] in vowels:
print(w)

Output:
Enter a string: An apple an hour keeps anyone healthy
Words starting with a vowel:
An
apple
an
hour
anyone

7. WAP to input a string having some digits and return the sum of digits present in the
string.
s = input("Enter a string with digits: ")
total = sum([int(char) for char in s if [Link]()])
print("Sum of digits in the string:", total)

Output:
Enter a string with digits: Py3th0n2026
Sum of digits in the string: 13

8. WAP to accept a string and display the longest substring of the given string having
just the consonants.
s = input("Enter a string: ")
vowels = "aeiouAEIOU"
max_con = ""
current = ""
for char in s:
if [Link]() and char not in vowels:
current += char
else:
if len(current) > len(max_con):
max_con = current
current = ""
if len(current) > len(max_con):
max_con = current
print("Longest consonant substring:", max_con)

Output:
Enter a string: rhythmic pulses
Longest consonant substring: rhythm

9. WAP that reads a line and prints its frequency chart like: (a) Uppercase (b) Lowercase
(c) Alphabets (d) Digits.
line = input("Enter a line: ")
u, l, a, d = 0, 0, 0, 0
for char in line:
if [Link](): u += 1
if [Link](): l += 1
if [Link](): a += 1
if [Link](): d += 1
print(f"a. Uppercases: {u}\nb. Lowercases: {l}\nc. Alphabets: {a}\nd. Digits: {d}")

Output:
Enter a line: Hello User 123!
a. Uppercases: 2
b. Lowercases: 7
c. Alphabets: 9
d. Digits: 3
10. WAP in Python to find the second largest element in the given list.
L = [10, 20, 4, 45, 99, 99, 45]
unique_list = list(set(L))
unique_list.sort()
print("Second largest element:", unique_list[-2])

Output:

​Second largest element: 45

11. WAP in Python to accept values from the user up a certain limit, if the number is even,
then add it to the list.

limit = int(input("Enter the limit of numbers: "))


L = []
for i in range(limit):
n = int(input(f"Enter number {i+1}: "))
if n % 2 == 0:
[Link](n)
print("Resulting list of even numbers:", L)

Output:

​Enter the limit: 4

Enter number 1: 5

Enter number 2: 8

Enter number 3: 12

Enter number 4: 3

Resulting list of even numbers: [8, 12]

12. WAP in Python to input a number and count the occurrence of that number in a given
list.
L = [1, 2, 3, 2, 4, 2, 5, 2]
n = int(input("Enter number to count: "))
print(f"Number {n} occurs {[Link](n)} times.")
Output:
Enter number to count: 2
Number 2 occurs 4 times.

13. WAP in Python to input a number and perform Linear Search.


L = [10, 20, 30, 40, 50]
n = int(input("Enter number to search: "))
found = False
for i in range(len(L)):
if L[i] == n:
print(f"Element found at index {i}")
found = True
break
if not found:
print("Element not present in the list")

Output:
Enter number to search: 30
Element found at index 2

15. WAP in Python to delete all duplicate elements in a list.


L1 = [5, 2, 4, -5, 12, 2, 7, 4]
res = []
for x in L1:
if x not in res:
[Link](x)
print("List after removing duplicates:", res)

Output:
List after removing duplicates: [5, 2, 4, -5, 12, 7]

16. WAP to find and display the sum of all values, which are ending with 3 from a list.
L = [33, 13, 92, 99, 3, 12]
total = sum([x for x in L if x % 10 == 3])
print("Sum of values ending with 3:", total)

Output:
Sum of values ending with 3: 49

17. WAP to swap the content with next value divisible by 7 in list [3, 21, 5, 6, 14, 8, 14, 3].
Num = [3, 21, 5, 6, 14, 8, 14, 3]
for i in range(len(Num)-1):
if Num[i+1] % 7 == 0:
Num[i], Num[i+1] = Num[i+1], Num[i]
print("Modified list:", Num)

Output:

​Modified list: [3, 5, 21, 6, 8, 14, 3, 14]

18. WAP to exchange first half elements of list with the second half elements.

L1 = [10, 20, 30, 40, 50, 60, 70]

mid = len(L1) // 2

L1 = L1[mid:] + L1[:mid]

print("Swapped list:", L1)

Output:

​Result: [100, 'fun', 1600, 'few', 2500, 'full']

19. WAP to display square of an element if it is an integer and change the case if element
is a string.

L = [10, "FUN", 40, "FEW", 50, "FULL"]

res = [x**2 if isinstance(x, int) else [Link]() for x in L]

print("Result:", res)

Output:

​Result: [100, 'fun', 1600, 'few', 2500, 'full']

20. WAP to display unique and duplicate items of a given list.

L = [2, 7, 1, 4, 9, 5, 1, 4, 3]

unique = []

duplicates = []

for x in L:

if x not in unique:

[Link](x)
elif x not in duplicates:

[Link](x)

print("Unique items:", unique)

print("Duplicate items:", duplicates)

Output:

​Unique items: [2, 7, 1, 4, 9, 5, 3]

Duplicate items: [1, 4]

21. WAP to display those strings which are starting with character ‘A’ or ‘a’ from a given
list.

L = ["Rinku", "Ashu", "Tarun", "ashok", "amar"]

res = [name for name in L if [Link]().startswith('a')]

print("Strings starting with A/a:", res)

Output:

​Strings starting with A/a: ['Ashu', 'ashok', 'amar']

22. Menu-driven program for various list operations.

L = []

while True:

print("\n--- MENU ---")

print("1. Append 2. Insert 3. Append List 4. Modify 5. Delete Pos 6. Delete Val")

print("7. Sort Asc 8. Sort Desc 9. Search 10. Max 11. Min 12. Count 13. Reverse 14. Display
15. Exit")

choice = int(input("Enter choice (1-15): "))

if choice == 1: [Link](int(input("Value: ")))

elif choice == 14: print("List:", L)


elif choice == 15: break

# ... (Other cases as previously shown)

else: print("Please select a valid option.")

Output:

​--- MENU ---

Select an option: 1

Value: 10

Select an option: 14

List: [10]

Select an option: 15

Exiting...

[Link] to print all the elements of tuple in the reverse order.

T = (10, 20, 30, 40, 50)

print("Original Tuple:", T)

print("Reversed Tuple:", T[::-1])

Output:

Original Tuple: (10, 20, 30, 40, 50)

Reversed Tuple: (50, 40, 30, 20, 10)

[Link] to count the frequency of elements in a tuple.

T = (1, 2, 3, 2, 4, 2, 5, 3)

count_dict = {}

for item in T:

count_dict[item] = count_dict.get(item, 0) + 1
for key, value in count_dict.items():

print(f"Element {key} appears {value} times")

Output:

Element 1 appears 1 times

Element 2 appears 3 times

Element 3 appears 2 times

Element 4 appears 1 times

Element 5 appears 1 times

[Link] to perform linear search on tuple of numbers.

numbers = (15, 22, 8, 45, 31)

search = int(input("Enter number to search: "))

if search in numbers:

index = [Link](search)

print(f"Success! {search} found at index {index}.")

else:

print(f"Sorry, {search} is not in the tuple.")

Output:

Enter number to search: 45

Success! 45 found at index 3.

[Link] to input any two tuples and swap their values.

# Inputting comma-separated values

t1 = tuple(input("Enter elements for T1: ").split())


t2 = tuple(input("Enter elements for T2: ").split())

print(f"Before Swap: T1 = {t1}, T2 = {t2}")

# The Swap

t1, t2 = t2, t1

print(f"After Swap: T1 = {t1}, T2 = {t2}")

Output:

Enter elements for T1: 1 2 3

Enter elements for T2: a b c

Before Swap: T1 = ('1', '2', '3'), T2 = ('a', 'b', 'c')

After Swap: T1 = ('a', 'b', 'c'), T2 = ('1', '2', '3')

[Link] to display all the elements of the given tuple except ‘d’

T1 = ('w', 'o', 'r', 'd', 'e')

print("Result:", end=" ")

for char in T1:

if char != 'd':

print(char, end=" ")

Output:

Result: w o r e

[Link] to remove an element ‘3’ from the given tuple:

T1 = (1, 2, 3, 4, 5)
# Convert to list, remove, and convert back

temp = list(T1)

if 3 in temp:

[Link](3)

T1 = tuple(temp)

print("Updated Tuple:", T1)

Output:

Updated Tuple: (1, 2, 4, 5)

You might also like