1.
write a program to check whether given number is Armstrong or not
# Python program to check if the number is an Armstrong number or not
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")
output:
Enter a number: 153
153 is an Armstrong number
[Link] a program to check whether given number is perfect or not
n = 78
Sum = 0
for i in range(1, n):
if(n % i == 0):
Sum = Sum + i
if (Sum == n):
print("Number is a Perfect Number.")
else:
print("Number is not a Perfect Number.")
output:
Number is not a Perfect Number
[Link] a program to find factorial of given number using recursive function
# Python 3 program to find
# factorial of given number
def factorial(n):
# Checking the number
# is 1 or 0 then
# return 1
# other wise return
# factorial
if (n==1 or n==0):
return 1
else:
return (n * factorial(n - 1))
# Driver Code
num = 5;
print("number : ",num)
print("Factorial : ",factorial(num))
Output
number : 5
Factorial : 120
[Link] a program to implement polymorphism
class Shape:
def area(self):
return "Undefined"
class Rectangle(Shape):
def __init__(self, length, width):
[Link] = length
[Link] = width
def area(self):
return [Link] * [Link]
class Circle(Shape):
def __init__(self, radius):
[Link] = radius
def area(self):
return 3.14 * [Link] ** 2
shapes = [Rectangle(2, 3), Circle(5)]
for shape in shapes:
print(f"Area: {[Link]()}")
output:
Area: 6
Area: 78.5
[Link] a python code to print try,except and finally block statements
# Python code to illustrate
# working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional
# Part as Answer
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)
finally:
# this block is always executed
# regardless of exception generation.
print('This is always executed')
# Look at parameters and note the working of Program
divide(3, 2)
divide(3, 0)
output:
Yeah ! Your answer is : 1
This is always executed
Sorry ! You are dividing by zero
This is always executed
[Link] a program to demonstrate string handling functions
# Python3 program to show the
# working of upper() function
text = 'heLLo for heLLo'
# upper() function to convert
# string to upper case
print("\nConverted String:")
print([Link]())
# lower() function to convert
# string to lower case
print("\nConverted String:")
print([Link]())
# converts the first character to
# upper case and rest to lower case
print("\nConverted String:")
print([Link]())
# swaps the case of all characters in the string
# upper case character to lowercase and viceversa
print("\nConverted String:")
print([Link]())
# convert the first character of a string to uppercase
print("\nConverted String:")
print([Link]())
# original string never changes
print("\nOriginal String")
print(text)
output:
Converted String:
HELLO FOR HELLO
Converted String:
hello for hello
Converted String:
Hello For Hello
Converted String:
HEllO FOR HEllO
Converted String:
Hello for hello
Original String
heLLo for heLLo
[Link] a python program to enter names of employees and their salaries as input and store
them in a dictionary
# Create an empty dictionary to store employee data
employee_data = {}
# Get the number of employees
n = int(input("Enter the number of employees: "))
# Loop to take employee name and salary input
for i in range(n):
name = input(f"Enter name of employee {i + 1}: ")
salary = float(input(f"Enter salary of {name}: "))
employee_data[name] = salary
# Display the dictionary
print("\nEmployee Data:")
for name, salary in employee_data.items():
print(f"Name: {name}, Salary: {salary}")
output:
Enter the number of employees: 2
Enter name of employee 1: abc
Enter salary of abc: 250000
Enter name of employee 2: xyz
Enter salary of xyz: 45000
Employee Data:
Name: abc, Salary: 250000.0
Name: xyz, Salary: 45000.0
[Link] a program to implement statistical operations on arrays using numpy
a. compute median for odd number of elements
import numpy as np
# create a 1D array with 5 elements
array1 = [Link]([1, 2, 3, 4, 5])
# calculate the median
median = [Link](array1)
print(median)
# Output: 3.0
[Link] mean using numpy
import numpy as np
# create a numpy array
marks = [Link]([76, 78, 81, 66, 85])
# compute the mean of marks
mean_marks = [Link](marks)
print(mean_marks)
# Output: 77.2
[Link] standard deviation using numpy
import numpy as np
# create a numpy array
marks = [Link]([76, 78, 81, 66, 85])
# compute the standard deviation of marks
std_marks = [Link](marks)
print(std_marks)
# Output: 6.803568381206575
[Link] data frame sales containing year wise sales and perform basic operations on it in
python
import pandas as pd
import [Link] as plt
# Create year-wise sales data
data = {
'Year': [2019, 2020, 2021, 2022, 2023],
'Sales': [15000, 18000, 21000, 19000, 25000]
}
# Create a DataFrame
sales = [Link](data)
# Display the DataFrame
print("Sales DataFrame:")
print(sales)
# Basic operations
print("\nDataFrame Info:")
print([Link]())
print("\nSummary Statistics:")
print([Link]())
# Accessing specific columns
print("\nSales Column:")
print(sales['Sales'])
# Filtering: Sales greater than 20000
print("\nYears with Sales > 20000:")
print(sales[sales['Sales'] > 20000])
# Add a new column: Increase in sales compared to previous year
sales['Increase'] = sales['Sales'].diff()
print("\nSales DataFrame with Increase column:")
print(sales)
# Plotting the sales trend
[Link](sales['Year'], sales['Sales'], marker='o', linestyle='-', color='green')
[Link]('Year-wise Sales Trend')
[Link]('Year')
[Link]('Sales')
[Link](True)
[Link]()
output:
Sales DataFrame:
Year Sales
0 2019 15000
1 2020 18000
2 2021 21000
3 2022 19000
4 2023 25000
DataFrame Info:
<class '[Link]'>
RangeIndex: 5 entries, 0 to 4
Data columns (total 2 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 Year 5 non-null int64
1 Sales 5 non-null int64
dtypes: int64(2)
memory usage: 208.0 bytes
None
Summary Statistics:
Year Sales
count 5.000000 5.000000
mean 2021.000000 19600.000000
std 1.581139 3721.558813
min 2019.000000 15000.000000
25% 2020.000000 18000.000000
50% 2021.000000 19000.000000
75% 2022.000000 21000.000000
max 2023.000000 25000.000000
[Link] the plot using matplotlib
[Link] chart
import [Link] as plt
x = [10, 20, 30, 40]
y = [20, 25, 35, 55]
[Link](x, y)
[Link]("Line Chart")
[Link]('Y-Axis')
[Link]('X-Axis')
[Link]()
[Link] chart
import [Link] as plt
import pandas as pd
data = pd.read_csv('[Link]')
x = data['day']
y = data['total_bill']
[Link](x, y)
[Link]("Tips Dataset")
[Link]('Total Bill')
[Link]('Day')
[Link]()
output: