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

Python Programming

The document contains multiple Python programs that demonstrate various functionalities such as string manipulation, file handling, mathematical calculations, data manipulation using pandas, and working with date-time. Each program is designed to accept user input and perform specific tasks, including extracting capitalized words, copying file contents, calculating the area of a circle, and generating random elements from sequences. Additionally, it covers creating dataframes, checking for Armstrong numbers, and formatting date-time strings.

Uploaded by

akanshawa2007
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 views11 pages

Python Programming

The document contains multiple Python programs that demonstrate various functionalities such as string manipulation, file handling, mathematical calculations, data manipulation using pandas, and working with date-time. Each program is designed to accept user input and perform specific tasks, including extracting capitalized words, copying file contents, calculating the area of a circle, and generating random elements from sequences. Additionally, it covers creating dataframes, checking for Armstrong numbers, and formatting date-time strings.

Uploaded by

akanshawa2007
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

1.

Write a python program to accept a string, extract all words that start with a capital letter and
remove all special characters from a string. Display modified string. (Accept input from user)

import re

# Accept input from user


text = input("Enter a string: ")

# Remove special characters (keep only letters, numbers, and spaces)


cleaned_text = [Link](r'[^A-Za-z0-9 ]', '', text)

# Extract words starting with a capital letter


words = cleaned_text.split()
capital_words = [word for word in words if word[0].isupper()]

# Display results
print("Modified string (without special characters):")
print(cleaned_text)

print("Words starting with a capital letter:")


print(capital_words)

Write a python program to accept file name. If file exist copy contents of one file into another file
and display contents of new file along with total number of lines, words and characters otherwise
give appropriate message.

# Accept file name


source_file = input("Enter source file name: ")
destination_file = input("Enter destination file name: ")

try:
# Check if source file exists and open it
with open(source_file, 'r') as f1:
content = [Link]()

# Copy content to new file


with open(destination_file, 'w') as f2:
[Link](content)

# Display contents of new file


print("\nContents of new file:")
print(content)
# Count lines, words, characters
lines = [Link]('\n')
words = [Link]()
characters = len(content)

print("\nTotal lines:", len(lines))


print("Total words:", len(words))
print("Total characters:", characters)

except FileNotFoundError:
print("File does not exist. Please check the file name.")

Write a python program to accepts value of radius from user and calculate the area of a circle using
function. (Use 3.14 as the value of π).

# Function to calculate area of circle


def calculate_area(radius):
area = 3.14 * radius * radius
return area

# Accept radius from user


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

# Call the function


result = calculate_area(r)

# Display result
print("Area of the circle is:", result)

Write a python program to create a list, string and tuple in python. Apply random module to
display unique multiple random elements from above created sequence type.

import random

# Create a list, string, and tuple


my_list = [10, 20, 30, 40, 50]
my_string = "PYTHON"
my_tuple = (1, 2, 3, 4, 5)

# Function to get unique random elements


def get_random_elements(sequence, count):
return [Link](sequence, count)

# Number of elements to pick


n = int(input("Enter number of random elements to select: "))

# Display results
print("\nRandom elements from list:", get_random_elements(my_list, n))
print("Random elements from string:", get_random_elements(my_string, n))
print("Random elements from tuple:", get_random_elements(my_tuple, n))

Write a python program to accepts a value of n and create a generator that yields even numbers up
to n.

# Generator function to yield even numbers up to n


def even_numbers(n):
for i in range(2, n + 1, 2):
yield i

# Accept input from user


n = int(input("Enter a value of n: "))

# Use the generator and display results


print("Even numbers up to", n, "are:")
for num in even_numbers(n):
print(num, end=" ")

Write a python program for following -


a) Create DataFrames Student 1, Student 2 and display contents
b) Join the two DataFrames in third frame with matching records from both sides.
c) Display Third DataFrame.
Student 1 Student 2
ID
Name
Age
0
S1
Anita
18
1
S2
Sakshi
23
2
S3
Om
20
3
S4
Raj
21
4
S5
Kanika
20

import pandas as pd

# Create Student 1 DataFrame


data1 = {
"ID": ["S1", "S2", "S3", "S4", "S5"],
"Name": ["Anita", "Sakshi", "Om", "Raj", "Kanika"],
"Age": [18, 23, 20, 21, 20]
}

student1 = [Link](data1)

# Create Student 2 DataFrame


data2 = {
"ID": ["S2", "S4", "S5", "S6", "S7"],
"City": ["Pune", "Nashik", "Mumbai", "Delhi", "Nanded"],
"Marks": [97, 78, 86, 66, 54]
}

student2 = [Link](data2)

# Display Student 1 and Student 2


print("Student 1 DataFrame:")
print(student1)

print("\nStudent 2 DataFrame:")
print(student2)

# Join both DataFrames on matching IDs (Inner Join)


student3 = [Link](student1, student2, on="ID", how="inner")
# Display third DataFrame
print("\nJoined DataFrame (Student 3):")
print(student3)

Write a python program using user define function to accept a number and perform the following
task:
a) Check number is Armstrong or not.
b) Calculate and display sum of digits till single digit [e.g. - 558 = 18 = 9]

# Function to check Armstrong number


def check_armstrong(num):
temp = num
order = len(str(num))
total = 0

while temp > 0:


digit = temp % 10
total += digit ** order
temp //= 10

if total == num:
return True
else:
return False

# Function to find sum of digits till single digit


def sum_to_single(num):
while num >= 10:
s=0
while num > 0:
s += num % 10
num //= 10
num = s
return num

# Accept input
n = int(input("Enter a number: "))

# Check Armstrong
if check_armstrong(n):
print("Number is Armstrong")
else:
print("Number is not Armstrong")

# Calculate single digit sum


result = sum_to_single(n)
print("Sum of digits till single digit:", result)

Write a python program to create a DataFrame from list of 10 integer values. Display contents of
DataFrame and calculate sum, mean, median, mode, Standard deviation of DataFrame.

import pandas as pd

# Create a list of 10 integer values


data = [10, 20, 30, 40, 50, 20, 30, 60, 70, 80]

# Create DataFrame
df = [Link](data, columns=["Numbers"])

# Display DataFrame
print("DataFrame:")
print(df)

# Calculations
print("\nSum:", df["Numbers"].sum())
print("Mean:", df["Numbers"].mean())
print("Median:", df["Numbers"].median())
print("Mode:", df["Numbers"].mode()[0])
print("Standard Deviation:", df["Numbers"].std())

Create a package finance_tools with modules [Link] and [Link]


a) [Link] should contain function cal_interest(amount, year) that accepts amount, year .
Calculates and returns simple interest using a fixed rate (for example, 5%).
b) [Link] should contain function converet(amount) that accepts amount in INR and converts
it into USD. (consider conversion rate 0.012)
Write a python program to import modules from finance_tools package and demonstrate both
functions.
# Module: [Link]

def cal_interest(amount, year):


rate = 0.05 # 5% interest rate
simple_interest = (amount * rate * year)
return simple_interest

# Module: [Link]

def cal_interest(amount, year):


rate = 0.05 # 5% interest rate
simple_interest = (amount * rate * year)
return simple_interest

# Module: [Link]

def convert(amount):
rate = 0.012 # INR to USD conversion rate
usd = amount * rate
return usd
# Import modules from package
from finance_tools import interest, currency

# Accept input
amt = float(input("Enter amount in INR: "))
years = int(input("Enter number of years: "))

# Call interest function


si = interest.cal_interest(amt, years)
print("Simple Interest:", si)

# Call currency conversion function


usd_value = [Link](amt)
print("Amount in USD:", usd_value)

[Link]
# This file can be empty (required to make it a package)

Write a Python program to create a class that acts as an iterator and generates the factorial series
up to n (1! + 2! + 3! + … + n!). (Accept input from the user)
# Class acting as an iterator for factorial series
class FactorialSeries:
def __init__(self, n):
self.n = n
[Link] = 1
[Link] = 1 # to store factorial

def __iter__(self):
return self

def __next__(self):
if [Link] > self.n:
raise StopIteration
else:
[Link] *= [Link]
result = [Link]
[Link] += 1
return result

# Accept input
n = int(input("Enter value of n: "))

# Create object
fs = FactorialSeries(n)

# Generate factorial series and sum


total = 0
print("Factorial series:")
for value in fs:
print(value, end=" ")
total += value

print("\nSum of factorial series:", total)

Write a python code to a create a list of 10 integer numbers. Display square of all elements of list.
(Use a lambda function with map())
# Create a list of 10 integer numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Use lambda function with map() to calculate square


squares = list(map(lambda x: x**2, numbers))

# Display result
print("Original list:", numbers)
print("Squares of elements:", squares)

Write a Python program that accepts a string from the user and performs the following tasks:
a) Split the string into individual words.
b) Identify and display all words that do not contain any vowels (a, e, i, o, u), ignore case while
checking for vowels.
c) Sort and display these words in alphabetical order.
d) Display the total count of such words.

# Accept string input from user


text = input("Enter a string: ")

# a) Split string into words


words = [Link]()

# b) Identify words without vowels (case-insensitive)


no_vowel_words = [word for word in words if not any(vowel in [Link]() for vowel in 'aeiou')]

# c) Sort words alphabetically


no_vowel_words.sort()

# d) Display results
print("\nWords without vowels:", no_vowel_words)
print("Total count of words without vowels:", len(no_vowel_words))

Create a [Link] file containing employee name, designation, salary of an employee. Write a
python program to create a DataFrame using [Link] and display the contents of DataFrame with
statistical information of dataframe.

Name,Designation,Salary
Anita,Manager,50000
Sakshi,Developer,40000
Om,Designer,35000
Raj,Developer,45000
Kanika,Manager,55000

import pandas as pd

# Read CSV file and create DataFrame


df = pd.read_csv('[Link]')

# Display the DataFrame


print("Employee DataFrame:")
print(df)

# Display statistical information


print("\nStatistical Information of DataFrame:")
print([Link]())

Write a Python program that:


a) Retrieves current local time and UTC time.
b) Prints the current time using ctime() and gmtime().
c) Accepts a date-time string input in the format DD-MM-YYYY HH:MM:SS.
d) Parses the string using strptime() and formats it back using strftime() and display it in two
custom formats.

import time
from datetime import datetime

# a) Retrieve current local time and UTC time


local_time = [Link]()
utc_time = [Link]()

print("Current Local Time:", [Link]("%Y-%m-%d %H:%M:%S", local_time))


print("Current UTC Time:", [Link]("%Y-%m-%d %H:%M:%S", utc_time))

# b) Print current time using ctime() and gmtime()


print("\nUsing ctime():", [Link]())
print("Using gmtime():", [Link](utc_time))

# c) Accept date-time string input


dt_str = input("\nEnter date-time (DD-MM-YYYY HH:MM:SS): ")

# d) Parse string using strptime


dt_obj = [Link](dt_str, "%d-%m-%Y %H:%M:%S")

# Format back using strftime in two custom formats


formatted1 = dt_obj.strftime("%A, %d %B %Y %I:%M:%S %p") # Example: Tuesday, 27 March 2026
05:30:00 PM
formatted2 = dt_obj.strftime("%Y/%m/%d %H-%M-%S") # Example: 2026/03/27 17-30-00

print("\nFormatted Date-Time (Format 1):", formatted1)


print("Formatted Date-Time (Format 2):", formatted2)

Write a python program to create a list, string and tuple in python. Apply random module to
display unique multiple random elements from above created sequence type.

import random

# Create a list, string, and tuple


my_list = [10, 20, 30, 40, 50]
my_string = "PYTHON"
my_tuple = (1, 2, 3, 4, 5)

# Ask user how many random elements to select


n = int(input("Enter number of random elements to select: "))

# Ensure n does not exceed length of sequences


n_list = min(n, len(my_list))
n_string = min(n, len(my_string))
n_tuple = min(n, len(my_tuple))

# Select unique random elements using [Link]()


rand_list = [Link](my_list, n_list)
rand_string = [Link](my_string, n_string)
rand_tuple = [Link](my_tuple, n_tuple)

# Display results
print("\nRandom elements from list:", rand_list)
print("Random elements from string:", rand_string)
print("Random elements from tuple:", rand_tuple)

You might also like