0% found this document useful (0 votes)
11 views12 pages

Python Programs for Number and String Operations

The document contains a series of programming questions and their corresponding Python code solutions, covering topics such as input validation, string manipulation, file handling, and data structures like stacks. Each question includes an input prompt and the expected output format. The solutions demonstrate various programming concepts and techniques in Python.

Uploaded by

mishra2008risha
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)
11 views12 pages

Python Programs for Number and String Operations

The document contains a series of programming questions and their corresponding Python code solutions, covering topics such as input validation, string manipulation, file handling, and data structures like stacks. Each question includes an input prompt and the expected output format. The solutions demonstrate various programming concepts and techniques in Python.

Uploaded by

mishra2008risha
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

Ques:1 - Write a program that inputs an integer in range 0 – 999 and then prints if the

integer entered is a 1/2/3 digit number.


Input:
num = int(input("Enter a number(0..999):"))
if num<0:
print("Invalid [Link] range is 0 to999.")
elif num<10:
print("Single digit number is entered")
elif num<100:
print("Two digit number is entered")
elif num<=999:
print("Three digit number is entered")
else:
print("invalid [Link] range is 0 to 999.")

Output:

Ques:2 WAP that inputs an integer in range 0-999 and then prints if the integer entered
is a 1/2/3 digit number. Use nested if statements.
Input:
num = int(input("Enter a number (0...999): "))
if num < 0 or num > 999:
print("Invalid entry. Valid range is 0 to 999.")
else:
if num < 10:
print("Single digit number is entered.")
else:
if num < 100:
print("Two digit number is entered.")
else:
print("Three digit number is entered.")

Output:
Ques:3 WAP a program that reads a line and prints its statics like:
Input:
line = input("Enter a line: ")
lowercount = uppercount = digitcount = alphacount = 0

for a in line:
if [Link]():
lowercount += 1
elif [Link]():
uppercount += 1
elif [Link]():
digitcount += 1
if [Link]():
alphacount += 1

print("Number of uppercase letters:", uppercount)


print("Number of lowercase letters:", lowercount)
print("Number of alphabets:", alphacount)
print("Number of digits:", digitcount)

Output:

Ques:4 write a program that read a string and checks whether it is a palindrome atring
or not.
Input:
string = input("Enter a string: ")
length = len(string)
mid = length // 2 # Use integer division
rev = -1

for a in range(mid):
if string[a] != string[rev]:
print(string, "is not a palindrome")
break
rev -= 1
else: # Correct usage of loop-else
print(string, "is a palindrome")
Output:
Ques:5 Program to add two numbers through a function.
Input:
# program [Link] to add two numbers through a function
def calcsum (x,y):
s= x+y #statement1
return s #statement2

num1 = float(input("Enter first number :")) #1(statement 1)


num2 = float(input("Enter second number:")) #2(statement 2)
sum =calcsum(num1,num2) #3(statement 3)
print("sum of two given numbers is",sum) #4(statement 4)

Output:

Ques:6 write a program to display the size of a file in bytes.


Input:
myfile = open(r'C:\[Link]',"r")
str = [Link]()
size = len(str)
print("size of the given file [Link] is")
print(size,"bytes")

Output:

Ques:7 write a program to display the number of lines in the file.


Input:
myfile = open(r'C:\[Link]',"r")
s = [Link]()
linecount = len(s)
print("Number of lines in [Link] is", linecount)
[Link]()
Output:

Ques:8 write a program to get a roll numbers,names and marks 0f the students of a
class (get from user) and store these details in a file called “[Link]”.

Input:
count = int(input("Hoe many students are there in the class?"))
fileout = open ("[Link]","w")

for i in range(count):
print("Enter details for student",(i+1),"below:")
rollno = int(input("rollno:"))
name = input("Name:")
marks = float(input("marks:"))
rec = str(rollno)+","+name+","+str(marks)+'\n'
[Link](rec)
[Link]()

Output:

Ques:9 write a program to add two more students’details to the file created in program
8.
Input:
fileout = open ("[Link]","a")

for i in range(2):
print("Enter deatils for student",(i+1),"below:")
rollno = int(input("rollno"))
name = input("Name:")
marks = float(input("Marks:"))
rec = str(rollno)+","+name+","+str(marks)+'\n'
[Link](rec)
[Link]()

Output:
Ques:10 write a program to append student records to file created in previous
program,by getting data fron user.
Input:
import pickle
#declare empty dictionary
stu = {}
# open file in append mode
stufile = open('[Link]','ab')
#getdata to write onto the file
ans = 'y'
while ans == 'y':
rno = int(input("Enter roll number:"))
name = input("Enter name:")
marks = float(input("Enter marks:"))
#add read data into dictionary
stu['rollno'] = rno
stu['name'] = name
stu['marks'] = marks
#now write into the file
[Link](stu,stufile)
ans = input("want to append more records?(y/n)...")
#close file
[Link]()
Output:

Ques:11 Write a program to open the file [Link], read the objects written in it and
display them.
Ques:12 WAP a program to open file created and used in previous programs and
display the student records stored in it
Input:
import pickle
stu = {} #declare empty dictionary object to hold read reacord
fin = open('[Link]','rb') #open binary file in read mode
#read from the file
try:
print("File [Link] stores these records")
while True: #it will become false upon EOF
stu = [Link](fin) #read record in stu dictionary from fin file handle
print(stu) #print the read record
except EOFError:
[Link]() #close file

Output:

Ques:13 WAP to create a CSV file to store syudent data (rollno.,name,marks).obtain


data fromUser and write 5 records into the file.
Input:
import csv
fh = open("[Link]","w")
stuwriter = [Link](fh)
[Link](['rollno','name','marks'])

for i in range(5):
print("student record",(i+1))
rollno =int(input("enter rollno:"))
name =input("enter name:")
marks = float(input("enter marks:"))
sturec = [rollno,name,marks] #create sequence of user data
[Link](sturec)

[Link]() #close file


Output:
Ques14: Write a program to implement a stack for these book-details(BOOK NO,BOOK
NAME).That is now each item node of the stack contains two type of information -a book
no and its name.
Input:
class BookStack:
def __init__(self):
# Initialize an empty stack
[Link] = []

def push(self, bookno, bookname):


# Push a dictionary containing book details onto the stack
[Link]({"BookNo": bookno, "BookName": bookname})
print(f'Book "{bookname}" (Book No: {bookno}) added to the stack.')

def pop(self):
# Pop a book from the stack
if self.is_empty():
print("The stack is empty. No books to remove.")
return None
book = [Link]()
print(f'Book "{book["BookName"]}" (Book No: {book["BookNo"]}) removed from the stack.')
return book

def peek(self):
# Peek at the top book on the stack without removing it
if self.is_empty():
print("The stack is empty. No books to display.")
return None
book = [Link][-1]
print(f'Top book: "{book["BookName"]}" (Book No: {book["BookNo"]})')
return book

def is_empty(self):
# Check if the stack is empty
return len([Link]) == 0

def display(self):
# Display all books in the stack
if self.is_empty():
print("The stack is empty. No books to display.")
else:
print("\nBooks in the stack:")
for i, book in enumerate(reversed([Link]), start=1):
print(f'{i}. "{book["BookName"]}" (Book No: {book["BookNo"]})')

# Main Program
def main():
book_stack = BookStack()

while True:
print("\nStack Operations:")
print("1. Push (Add a Book)")
print("2. Pop (Remove a Book)")
print("3. Peek (View Top Book)")
print("4. Display Stack")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == "1":
bookno = input("Enter the book number: ").strip()
bookname = input("Enter the book name: ").strip()
book_stack.push(bookno, bookname)
elif choice == "2":
book_stack.pop()
elif choice == "3":
book_stack.peek()
elif choice == "4":
book_stack.display()
elif choice == "5":
print("Exiting the program.")
break
else:
print("Invalid choice! Please enter a number between 1 and 5.")

# Run the program


main()
output:
Ques15: Write a program that reads a string and checks wether it is palindrome or not.
Input:
def is_palindrome(string):
"""
Function to check if a string is a palindrome.
A palindrome reads the same forward and backward.
"""
# Remove spaces and convert to lowercase for uniformity
cleaned_string = ''.join([Link]() for char in string if [Link]())

# Check if the string is equal to its reverse


return cleaned_string == cleaned_string[::-1]

# Input from the user


user_input = input("Enter a string to check if it's a palindrome: ")

# Check and display result


if is_palindrome(user_input):
print(f"'{user_input}' is a palindrome.")
else:
print(f"'{user_input}' is not a palindrome.")
Output:
Ques16:Write a python program to Push,pop,peekand display on item in stack.
Input:
class Stack:
def __init__(self):
[Link] = []

def push(self, item):


"""Add an item to the stack."""
[Link](item)
print(f"{item} pushed to stack.")

def pop(self):
"""Remove and return the top item of the stack."""
if not self.is_empty():
removed_item = [Link]()
print(f"Popped item: {removed_item}")
return removed_item
else:
print("Stack is empty. Cannot pop.")

def peek(self):
"""Return the top item of the stack without removing it."""
if not self.is_empty():
print(f"Top item: {[Link][-1]}")
return [Link][-1]
else:
print("Stack is empty. No top item.")

def display(self):
"""Display the items in the stack."""
if not self.is_empty():
print("Stack items:", [Link])
else:
print("Stack is empty.")

def is_empty(self):
"""Check if the stack is empty."""
return len([Link]) == 0

# Example usage
if __name__ == "__main__":
stack = Stack()

while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
choice = input("Enter your choice (1-5): ")

if choice == "1":
item = input("Enter the item to push: ")
[Link](item)
elif choice == "2":
[Link]()
elif choice == "3":
[Link]()
elif choice == "4":
[Link]()
elif choice == "5":
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
Output:
Ques17: write a program to get item details (code,description,price)for multiple items
from the user and create a csv file by writing all the items details in one go.
Input:
import csv
fh = open("[Link]","w")
iwriter = [Link](fh)
ans = 'y'
itemrec= [['item_name','description','price']]
print("enter item details")
while ans =='y':
iname = input("enter item code:")
desc = input("enter description:")
price = float(input("enter price:"))
[Link]( [iname,desc,price])
ans = input("want to enter more items? (y/n)...")
[Link](itemrec)
print("records written successfully.")
[Link]()
Output:

You might also like