0% found this document useful (0 votes)
0 views

S Python Most Asked Programs

The document contains a collection of Python programs addressing common programming tasks, including calculating factorials, swapping tuples, handling exceptions, checking palindromes, summing digits, and working with lists and sets. It also includes class definitions for managing student information and demonstrates file handling and random number generation. Each program is presented with code snippets and brief explanations of their functionality.

Uploaded by

kolawaranushree
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)
0 views

S Python Most Asked Programs

The document contains a collection of Python programs addressing common programming tasks, including calculating factorials, swapping tuples, handling exceptions, checking palindromes, summing digits, and working with lists and sets. It also includes class definitions for managing student information and demonstrates file handling and random number generation. Each program is presented with code snippets and brief explanations of their functionality.

Uploaded by

kolawaranushree
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
You are on page 1/ 9

Python Most Asked Programs

1. Write a Python program to find the factorial of a number provided by the user.
# Program to find the factorial of a number

# Get input from user


num = int(input("Enter a number to find its factorial: "))

# Factorial of negative numbers doesn't exist


if num < 0:
print("Factorial does not exist for negative numbers.")
elif num == 0:
print("The factorial of 0 is 1.")
else:
factorial = 1
for i in range(1, num + 1):
factorial *= i
print(f"The factorial of {num} is {factorial}.")

2. Write a python program to input any two tuples and interchange the tuple variables
# Input two tuples from the user
tuple1 = tuple(input("Enter elements of first tuple separated by space: ").split())
tuple2 = tuple(input("Enter elements of second tuple separated by space: ").split())

# Display before swapping


print("\nBefore swapping:")
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)

# Swapping the tuples


tuple1, tuple2 = tuple2, tuple1
# Display after swapping
print("\nAfter swapping:")
print("Tuple 1:", tuple1)
print("Tuple 2:", tuple2)

3. Write a program to show user defined exception in Python


# Define a user-defined exception
class NegativeNumberError(Exception):
"""Exception raised for entering a negative number."""
pass

# Function to check positive number


def check_positive(number):
if number < 0:
raise NegativeNumberError("Negative numbers are not allowed.")
else:
print(f"{number} is a valid positive number.")

# Main program
try:
num = int(input("Enter a positive number: "))
check_positive(num)
except NegativeNumberError as e:
print("User Defined Exception Caught:", e)
except ValueError:
print("Please enter a valid integer.")

4. Write a Python Program to check if a string is palindrome or not.


# Get input from the user
text = input("Enter a string: ")
# Convert the string to lowercase and remove spaces for uniformity (optional)
cleaned_text = text.replace(" ", "").lower()

# Check if the string is equal to its reverse


if cleaned_text == cleaned_text[::-1]:
print(f'"{text}" is a palindrome.')
else:
print(f'"{text}" is not a palindrome.')

5. Write a Python program to calculate sum of digit of given number using function.
# Function to calculate sum of digits
def sum_of_digits(number):
total = 0
while number > 0:
digit = number % 10
total += digit
number //= 10
return total

# Get input from the user


num = int(input("Enter a number: "))

# Call the function and display the result


print("Sum of digits:", sum_of_digits(num))

6. Write a Python Program to accept values from user in a list and find the largest
number and smallest number in a list.
# Accept values from the user
numbers = list(map(int, input("Enter numbers separated by space: ").split()))
# Check if the list is not empty
if numbers:
largest = max(numbers)
smallest = min(numbers)

print("List of numbers:", numbers)


print("Largest number:", largest)
print("Smallest number:", smallest)
else:
print("The list is empty. Please enter some numbers.")

7. Design a class student with data members : name, roll no., department, mobile no.
Create suitable methods for reading and printing student information
class Student:
def __init__(self):
self.name = ""
self.roll_no = ""
self.department = ""
self.mobile_no = ""

def read_info(self):
self.name = input("Enter student's name: ")
self.roll_no = input("Enter roll number: ")
self.department = input("Enter department: ")
self.mobile_no = input("Enter mobile number: ")

def display_info(self):
print("\n--- Student Information ---")
print("Name :", self.name)
print("Roll No. :", self.roll_no)
print("Department :", self.department)
print("Mobile No. :", self.mobile_no)
# Main program
student1 = Student()
student1.read_info()
student1.display_info()

8. Write python program to perform following operations on set. i) Create set of five
elements ii) Access set elements iii) Update set by adding one element iv) Remove
one element from set.
# i) Create a set of five elements
my_set = {10, 20, 30, 40, 50}
print("Original Set:", my_set)

# ii) Access set elements (using a loop since sets are unordered)
print("\nAccessing set elements:")
for item in my_set:
print(item)

# iii) Update set by adding one element


my_set.add(60)
print("\nSet after adding 60:", my_set)

# iv) Remove one element from set


my_set.remove(30) # Make sure the element exists before removing
print("Set after removing 30:", my_set)

9. Write a python program to create a user defined module that will ask your program
name and display the name of the program.
# my_module.py

def ask_program_name():
name = input("Enter the name of your program: ")
print(f"The name of your program is: {name}")

# main_program.py

import my_module

# Call the function from the module


my_module.ask_program_name()

10. Write a python program takes in a number and find the sum of digits in a number.
Refer q. 5

11. Write a program function that accepts a string and calculate the number of
uppercase letters and lower case letters.
def count_case_letters(text):
upper_count = 0
lower_count = 0

for char in text:


if char.isupper():
upper_count += 1
elif char.islower():
lower_count += 1

print("Uppercase letters:", upper_count)


print("Lowercase letters:", lower_count)

# Main program
input_string = input("Enter a string: ")
count_case_letters(input_string)
12. Write a python program to create class student with roll-no and display its
contents.
class Student:
def __init__(self, roll_no):
self.roll_no = roll_no

def display(self):
print(f"Student Roll Number: {self.roll_no}")

# Main program
roll_number = input("Enter student roll number: ")
student1 = Student(roll_number)
student1.display()

13. Write a python program to generate five random integers between 10 and 50 using
numpy library.
import numpy as np

# Generate 5 random integers between 10 and 50


random_integers = np.random.randint(10, 51, 5)

# Display the generated integers


print("Random integers between 10 and 50:", random_integers)

14. Write a Python program to check for zero division errors exception.
# Function to perform division
def divide_numbers(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
else:
print(f"The result of {a} / {b} is: {result}")

# Main program
num1 = float(input("Enter the numerator: "))
num2 = float(input("Enter the denominator: "))

divide_numbers(num1, num2)

15. Write a Python program to read contents from “a.txt” and write same contents in
“b.txt”
# Open "a.txt" in read mode and "b.txt" in write mode
try:
with open("a.txt", "r") as file_a:
contents = file_a.read() # Read all contents from a.txt

with open("b.txt", "w") as file_b:


file_b.write(contents) # Write the contents to b.txt

print("Contents copied successfully from 'a.txt' to 'b.txt'.")

except FileNotFoundError:
print("Error: One of the files (a.txt or b.txt) does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

16. Design a class student with data members; Name, Roll No., Address. Create
suitable method for reading and printing students details.
class Student:
def __init__(self):
self.name = ""
self.roll_no = ""
self.address = ""

def read_details(self):
self.name = input("Enter student's name: ")
self.roll_no = input("Enter roll number: ")
self.address = input("Enter address: ")

def display_details(self):
print("\n--- Student Details ---")
print(f"Name : {self.name}")
print(f"Roll No. : {self.roll_no}")
print(f"Address : {self.address}")

# Main program
student1 = Student()
student1.read_details() # Reading student details
student1.display_details() # Displaying student details

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy