0% found this document useful (0 votes)
5 views20 pages

Python Programs

The document contains a collection of Python programs that demonstrate various string, tuple, list, and dictionary operations. Each program includes a specific task such as checking string equality, counting characters, manipulating lists, and managing dictionaries. The examples are designed to help users understand fundamental programming concepts in Python.

Uploaded by

suhasgowdack
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)
5 views20 pages

Python Programs

The document contains a collection of Python programs that demonstrate various string, tuple, list, and dictionary operations. Each program includes a specific task such as checking string equality, counting characters, manipulating lists, and managing dictionaries. The examples are designed to help users understand fundamental programming concepts in Python.

Uploaded by

suhasgowdack
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

STRINGS

Q) WAP to Check whether two strings are equal or greater (order)

str1 = input(“Enter the first string: ”)


str2 = input(“Enter the second string: ”)
sorted_str1 = "".join(sorted(str1))
sorted_str2 = "".join(sorted(str2))
if sorted_str1 == sorted_str2:
print("Both strings are equal (in sorted order)")
elif sorted_str1 > sorted_str2:
print(sorted_str1, "is greater than", sorted_str2)
else:
print(sorted_str2, "is greater than", sorted_str1)

Q) WAP to check whether two strings are equal ignoring the case

str1 = input(“Enter the first string: ”)


str2 = input(“Enter the second string: ”)
if [Link]() == [Link]():
print("Both strings are equal (ignoring case)")
else:
print("Strings are not equal")

Q) WAP to check whether a given string is palindrome or not

string = "racecar"
reversed_str = ""
for char in string:
reversed_str = char + reversed_str
if string == reversed_str:
print(string, "is a Palindrome")
else:
print(string, "is NOT a Palindrome")

Q) WAP to check presence of characters in a string

string = "Hello, World!"


char = "W"
if char in string:
print(char, "is present in the string")
else:
print(char, "is NOT present in the string")

Q) WAP to find substring position using find()

string = "Python is fun and Python is easy"


substring = "Python"
position = string.find(substring)
if position != -1:
print("Substring found at index:", position)
else:
print("Substring not found")

Q) WAP to count occurrences of a character in a string

string = "banana"
char = "a"
count = [Link](char)
print(char, "appears", count, "time(s) in", string)

Q) WAP to count occurrences of a character WITHOUT using count()

string = "banana"
char = "a"
count = 0
for letter in string:
if letter == char:
count = count + 1
print(char, "appears", count, "time(s) in", string)

Q) WAP to count vowels in a string

string = "Hello World"


vowels = "aeiouAEIOU"
count = 0
for char in string:
if char in vowels:
count = count + 1
print("Number of vowels in", string, ":", count)

Q) WAP to count consonants in a string

string = "Hello World"


vowels = "aeiouAEIOU"
count = 0
for char in string:
if [Link]() and char not in vowels:
count = count + 1
print("Number of consonants in", string, ":", count)
Q) WAP to reverse a string (without slicing)

string = "Python"
reversed_str = ""
for char in string:
reversed_str = char + reversed_str
print("Original :", string)
print("Reversed :", reversed_str)

Q) WAP to count words in a sentence

sentence = "Python is a great programming language"


words = [Link]()
print("Sentence :", sentence)
print("Word count:", len(words))

Q) WAP to remove spaces in a string

string = "Hello World How Are You"


no_spaces = ""
for char in string:
if char != " ":
no_spaces = no_spaces + char
print("Original :", string)
print("No Spaces:", no_spaces)
Q) WAP to replace vowels in a string with *

string = "Hello World"


vowels = "aeiouAEIOU"
result = ""
for char in string:
if char in vowels:
result = result + "*"
else:
result = result + char
print("Original :", string)
print("Modified :", result)

Q) WAP to convert a string to uppercase (without built-in upper())

string = "hello world"


result = ""
for char in string:
if "a" <= char <= "z":
result = result + chr(ord(char)-32) #ord()gives the ASCII code of character
else: #32 is the difference between upper and lower case
result = result + char
print("Original :", string)
print("Uppercase :", result)

Q) WAP to check if a substring exists in a string or not

string = "Python programming is fun"


substring = "programming"
if substring in string:
print(substring, "EXISTS in the string")
else:
print(substring, "does NOT exist in the string")

Q) WAP to count digits and alphabets in a string

string = "Hello123World456"
digits = 0
alphabets = 0
for char in string:
if [Link]():
digits = digits + 1
elif [Link]():
alphabets = alphabets + 1
print("String :", string)
print("Alphabets :", alphabets)
print("Digits :", digits)

Q) WAP to find the longest word in a sentence or string

sentence = "Python is an amazing programming language"


words = [Link]()
longest = ""
for word in words:
if len(word) > len(longest):
longest = word
print("Sentence :", sentence)
print("Longest word :", longest)

Q) WAP to remove duplicate characters in a string

string = "programming"
result = ""
for char in string:
if char not in result:
result = result + char
print("Original :", string)
print("No Dupes :", result)

Q) WAP to count special characters in a string


string = "Hello! How are you? #Python @2024"
count = 0
for char in string:
if not [Link]() and not [Link]() and char != " ":
count = count + 1
print("String :", string)
print("Special chars :", count)

TUPLE

Q) Create a list of student records comprising name & age and display using for loop

students = [("Alice", 20), ("Bob", 22), ("Charlie", 21), ("Diana", 19)]


print("Student Records:")
for student in students:
name = student[0]
age = student[1]
print("Name:", name, " Age:", age)

Q) WAP to return multiple values by reading two integers after performing addition and
multiplication

#Function
def mul_val(a, b):
addition = a + b
multiplication = a * b
return addition, multiplication

#Main Program
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
add, mul = mul_val(num1, num2)
print("Addition :", add)
print("Multiplication :", mul)

LIST

Q) WAP using a list to read n elements and check whether each number is odd or even

n = int(input("How many elements? "))


numbers = []
for i in range(n):
num = int(input("Enter element no." + str(i + 1) + ": "))
[Link](num)
print("List:", numbers)
for num in numbers:
if num % 2 == 0:
print(num, "is Even")
else:
print(num, "is Odd")

Q) WAP to generate a list of squares of n numbers using function

#Function
def generate_squares(n):
squares = []
for i in range(1, n + 1):
[Link](i * i)
return squares

#Main program
n = int(input("Enter value of n: "))
result = generate_squares(n)
print("Squares of first", n, "numbers:")
print(result)

Q) Define a function to check whether given number is prime or not. Read n elements into a list
and check using the function

#Function
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True

#Main program
n = int(input("How many elements? "))
numbers = []
for i in range(n):
num = int(input("Enter element no." + str(i + 1) + ": "))
[Link](num)
print("List:", numbers)
for num in numbers:
if is_prime(num):
print(num, "is Prime")
else:
print(num, "is not Prime")

Q) WAP to create a list of n numbers and find its sum

n = int(input("How many numbers? "))


numbers = []
for i in range(n):
num = int(input("Enter number: "))
[Link](num)
total = 0
for num in numbers:
total = total + num
print("List :", numbers)
print("Sum :", total)

Q) WAP to create a list of n numbers and find the maximum or largest element

n = int(input("How many numbers? "))


numbers = []
for i in range(n):
num = int(input("Enter number: "))
[Link](num)
largest = numbers[0]
for num in numbers:
if num > largest:
largest = num
print("List :", numbers)
print("Maximum :", largest)

Q) WAP to create a list of integers and remove duplicate elements

numbers = [1, 2, 3, 2, 4, 1, 5, 3, 6]


new_list = []
for num in numbers:
if num not in new_list:
new_list.append(num)
print("Original List:", numbers)
print("After Removing Duplicates:", new_list)

Q) WAP to add two matrices by reading rows, columns, and elements from the user

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


cols = int(input("Enter number of columns: "))
matrix1 = []
matrix2 = []
result = []
print("Enter elements of Matrix 1:")
for i in range(rows):
row = []
for j in range(cols):
val = int(input("element [" + str(i) + "][" + str(j) + "]: "))
[Link](val)
[Link](row)
print("Enter elements of Matrix 2:")
for i in range(rows):
row = []
for j in range(cols):
val = int(input("element [" + str(i) + "][" + str(j) + "]: "))
[Link](val)
[Link](row)
for i in range(rows):
row = []
for j in range(cols):
[Link](matrix1[i][j] + matrix2[i][j])
[Link](row)
print("Sum of Matrices:")
for row in result:
print(row)

Dictionaries

Q)WAP to create a dictionary of n students comprising reg no. and name, Display the details

n = int(input("How many students? "))


students = {}
for i in range(n):
reg = input("Enter reg no: ")
name = input("Enter name: ")
students[reg] = name
print("Student Details:")
print("-" * 30)
for reg in students:
print("Reg No:", reg, " Name:", students[reg])

Q)WAP to construct frequency table of the letters in the string. Also display the frequency table in
alphabetical order

string = input("Enter a string: ")


freq = {}
for char in string:
if char != " ":
if char in freq:
freq[char] = freq[char] + 1
else:
freq[char] = 1
print("Frequency Table (Alphabetical Order):")
print("-" * 30)
for char in sorted(freq):
print(char, ":", freq[char])

Q) WAP to check for existence of a key in a dictionary

students = {"101": "Alice", "102": "Bob", "103": "Charlie"}


key = input("Enter reg no to search: ")
if key in students:
print("Key found! Name:", students[key])
else:
print("Key not found in dictionary")

Q) WAP to count frequency of characters without using get() method


string = input("Enter a string: ")
freq = {}
for char in string:
if char != " ":
if char in freq:
freq[char] = freq[char] + 1
else:
freq[char] = 1
print("Character Frequency:")
for char in freq:
print(char, "->", freq[char])

Q) WAP to find sum of dictionary values

marks = {"Maths": 85, "Science": 90, "English": 78, "History": 88}


total = 0
for subject in marks:
total = total + marks[subject]
print("Marks Dictionary:", marks)
print("Total Sum of Values:", total)

Q) WAP to count words in a sentence using dictionary

sentence = input("Enter a sentence: ")


words = [Link]()
word_count = {}
for word in words:
if word in word_count:
word_count[word] = word_count[word] + 1
else:
word_count[word] = 1
print("Word count:")
for word in word_count:
print(word, ":", word_count[word])
Q) WAP to count vowels in a string using dictionary

string = input("Enter a string: ")


vowels = "aeiouAEIOU"
vowel_count = {}
for char in string:
if char in vowels:
if char in vowel_count:
vowel_count[char] = vowel_count[char] + 1
else:
vowel_count[char] = 1
print("Vowel frequency:")
for v in vowel_count:
print(v, ":", vowel_count[v])

Q) WAP to count digits in a number using dictionary

number = input("Enter a number: ")


digit_count = {}
for digit in number:
if digit in digit_count:
digit_count[digit] = digit_count[digit] + 1
else:
digit_count[digit] = 1
print("Digit frequency in", number, ":")
for digit in digit_count:
print(digit, ":", digit_count[digit])

Numpy

Q) WAP using numpy to add two matrices. Read order of matrix and elements
import numpy as np
rows = int(input("Enter number of rows: "))
cols = int(input("Enter number of columns: "))
print("Enter elements of Matrix 1:")
matrix1 = []
for i in range(rows):
row = []
for j in range(cols):
val = int(input("element [" + str(i) + "][" + str(j) + "]: "))
[Link](val)
[Link](row)
print("Enter elements of Matrix 2:")
matrix2 = []
for i in range(rows):
row = []
for j in range(cols):
val = int(input("element [" + str(i) + "][" + str(j) + "]: "))
[Link](val)
[Link](row)
a = [Link](matrix1)
b = [Link](matrix2)
result = a + b
print("Matrix 1:")
print(a)
print("Matrix 2:")
print(b)
print("Sum of Matrices:")
print(result)

Q) WAP using numpy to multiply two matrices. Read order of matrices and elements

import numpy as np


rows1 = int(input("Enter rows of Matrix 1: "))
cols1 = int(input("Enter columns of Matrix 1: "))
rows2 = int(input("Enter rows of Matrix 2: "))
cols2 = int(input("Enter columns of Matrix 2: "))
print("Enter elements of Matrix 1:")
matrix1 = []
for i in range(rows1):
row = []
for j in range(cols1):
val = int(input("element [" + str(i) + "][" + str(j) + "]: "))
[Link](val)
[Link](row)
print("Enter elements of Matrix 2:")
matrix2 = []
for i in range(rows2):
row = []
for j in range(cols2):
val = int(input("element [" + str(i) + "][" + str(j) + "]: "))
[Link](val)
[Link](row)
a = [Link](matrix1)
b = [Link](matrix2)
result = [Link](a, b)
print("Matrix 1:")
print(a)
print("Matrix 2:")
print(b)
print("Product of Matrices:")
print(result)

Q) WAP to read n elements into a numpy array and find its average

import numpy as np


n = int(input("How many elements? "))
elements = []
for i in range(n):
val = float(input("Enter element " + str(i + 1) + ": "))
[Link](val)
arr = [Link](elements)
avg = [Link](arr)
print("Array :", arr)
print("Average :", avg)

Q) WAP to read n elements into a numpy array and find the average of elements greater than a
given value

import numpy as np


n = int(input("How many elements? "))
elements = []
for i in range(n):
val = float(input("Enter element " + str(i + 1) + ": "))
[Link](val)
arr = [Link](elements)
threshold = float(input("Enter the value to compare: "))
greater = arr[arr > threshold]
if len(greater) == 0:
print("No elements greater than", threshold)
else:
avg = [Link](greater)
print("Elements greater than", threshold, ":", greater)
print("Average of those elements:", avg)

Q) WAP to read n elements into a numpy array and count occurrence of each element

import numpy as np


n = int(input("How many elements? "))
elements = []
for i in range(n):
val = int(input("Enter element " + str(i + 1) + ": "))
[Link](val)
arr = [Link](elements)
unique, counts = [Link](arr, return_counts=True)
print("Array:", arr)
print("Element Count")
print("-" * 20)
for i in range(len(unique)):
print(unique[i], "occurs:", counts[i])

Files

Q)WAP to create a file with few lines of text. Display the contents of the file created line by line

# Creating the file


f = open("myfi[Link]", "w")
[Link]("Hello, this is line 1\n")
[Link]("Python is fun to learn\n")
[Link]("This is line 3\n")
[Link]("File handling is easy\n")
[Link]()
print("File created successfully!")
print()

# Reading and displaying line by line


f = open("myfi[Link]", "r")
print("Contents of the file:")
print("-" * 30)
for line in f:
print(line, end="")
[Link]()
Q) WAP to read a file comprising name and email address one per line. Sort the list of names and
write it to another file. Display the contents of the new file created

# First create the input file


f = open("[Link]", "w")
[Link]("Charlie charlie@[Link]\n")
[Link]("Alice alice@[Link]\n")
[Link]("Diana diana@[Link]\n")
[Link]("Bob bob@[Link]\n")
[Link]()

# Read the file


f = open("[Link]", "r")
lines = [Link]()
[Link]()

#Sorting and adding the sorted data


[Link]()
f = open("sorted_contacts.txt", "w")
for line in lines:
[Link](line)
[Link]()

# Display new file contents


f = open("sorted_contacts.txt", "r")
print("Sorted contacts:")
print("-" * 30)
for line in f:
print(line, end="")
[Link]()

Q) WAP to read a file and display its contents Count the number of words in the file

f = open("[Link]", "w")
[Link]("Python is a great programming language\n")
[Link]("It is easy to learn and use\n")
[Link]("File handling is one of its features\n")
[Link]()
f = open("[Link]", "r")
content = [Link]()
[Link]()
print("File Contents:")
print("-" * 30)
print(content)
words = [Link]()
print("Total number of words:", len(words))

You might also like