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

Pythonfile

The document contains various Python programs demonstrating different functionalities such as finding the greatest value among three numbers, creating patterns, using recursion, handling data with pandas, and visualizing data with matplotlib. Each program is accompanied by its output, showcasing practical applications of programming concepts. The examples cover a wide range of topics, including arrays, data frames, and graphical representations.

Uploaded by

sabby13
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 views37 pages

Pythonfile

The document contains various Python programs demonstrating different functionalities such as finding the greatest value among three numbers, creating patterns, using recursion, handling data with pandas, and visualizing data with matplotlib. Each program is accompanied by its output, showcasing practical applications of programming concepts. The examples cover a wide range of topics, including arrays, data frames, and graphical representations.

Uploaded by

sabby13
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/ 37

# Progarm of find Greatest value

a=int(input(" enter the value"))


b = int(input(" enter the value"))
c=int(input("enter the value "))
print("value of a=",a)
print("value of b=",b)
print("value of c=",c)
if a > b and a>c:
print("a is greatest value",a)
elif b>a and b>c:
print(" b is greatest value",b)
else:
print("c is greatest value",c)

OUTPUT:-
# Python program to print diamond star pattern using for
loop

# take input

n =int(input("enter value "))

# printing pyramid

for i in range(n):

for j in range(n-i-1):

# print spaces

print("", end=" ")

for j in range(2*i+1):

# print stars

print("*", end="")

print()

# printing downward pyramid

for i in range(n-1):

for j in range(i+1):

# print spaces

print("", end=" ")

for j in range(2*(n-i-1)-1):

# print stars

print("*", end="")

print()
OUTPUT:-
# Program of Function Recursion
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result

print("\n\nRecursion Results")
tri_recursion(6)

OUTPUT:-
# Program to create module
Data = {
"name": "John",
"age": 36,
"country": "Norway"
}
print("The result is =",Data)

OUTPUT:-
# Program of call mod module which is created by user

import mod

a = mod.Data["age"]
print(“value after calling module in this program”,a)

OUTPUT:-
# Python program to find duplicate items in list

# take list
my_list = [1, 3, 7, 1, 2, 7, 5, 3, 8, 1]

# printing original list


print('List:', my_list)

# find duplicate items using set()


seen = set()
duplicate_item = [x for x in my_list if x in seen or (seen.add(x) or False)]

# printing duplicate elements


print('Duplicate Elements:', duplicate_item)

OUTPUT:-
# Program to read data from text file

f = open("lk.txt", "r")
print(f.read())
f = open("kl.txt", "a")
f.write("add new content in file")
f.close()

#open and read the file after the appending:


f = open("kl.txt", "r")
print(f.read())

OUTPUT:-
# Program of one dimension array by nympy

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print("creation of one dimension array",arr)

print("type of array",type(arr))

OUTPUT:-
# Program of two dimension array by numpy

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(" presentation of 2d array \n",arr)

OUTPUT:-
# Program Addition of two array
import numpy as np
m1 = np.array([[3, 4], [5, 6]])
m2 = np.array([[8, 9], [0, 6]])
print(" 1st array= \n",m1)
print(" 2nd array= \n ",m2)
r = np.add(m1, m2)
print("The result after addition of arr m1 and arrm2 \n",r)

OUTPUT:-
# Program of slicing of one demission array

import numpy as np

arr = np.array([3,4,3,2,4,5,34,5,4,6,78])
print(arr)

print('values of array after slicing',arr[1:5])

OUTPUT:-
# Program of slicing on two Dimension array

import numpy as np

arr = np.array([[11, 25, 37, 44, 35], [16, 27, 18, 93, 10]])
print(" Array before Slicing \n",arr)

print('vales of after slicing\n',arr[0:2, 1:4])

OUTPUT:_
# Program of indexing one demission array

import numpy as np

arr = np.array([1, 2, 3, 4])


print("print values according to indexing",arr[0])
print(arr[2] + arr[3])

OUTPUT:-
# Program of Indexing on Two Dimension array

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])


print( "simple array\n",arr)

print('5th element on 2nd row: ', arr[1, 4],"\n 4th element of first row",arr[0,3])

OUTPUT:-
# Program of Negative indexing of 2d array

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])


print("array is = \n",arr)

print('Last element from 2nd dim: ', arr[1, -1])

OUTPUT:-
# Program of create simple data frame

import pandas as pd

data = {
"calories": [420, 380, 390],
"duration": [50, 40, 45]
}

#load data into a DataFrame object:


df = pd.DataFrame(data)

print(df)

OUTPUT:-
# program to create Data frame by csv file
import pandas as pd

df = pd.read_csv('data.csv')

print(df)

OUTPUT:-
# Program of data frame on given data
import pandas as pd

data = {
"Duration":{
"0":60,
"1":60,
"2":60,
"3":45,
"4":45,
"5":60
},
"Pulse":{
"0":110,
"1":117,
"2":103,
"3":109,
"4":117,
"5":102
},
"Maxpulse":{
"0":130,
"1":145,
"2":135,
"3":175,
"4":148,
"5":127
},
"Calories":{
"0":409,
"1":479,
"2":340,
"3":282,
"4":406,
"5":300
}
}

df = pd.DataFrame(data)

print(df)
OUTPUT:-
#program of printing the first 10 rows of the Data Frame

import pandas as pd

df = pd.read_csv('data.csv')

print(df.head(10))

OUTPUT:-
# Program of a new Data Frame with no empty cells

import pandas as pd

df = pd.read_csv('data.csv')

new_df = df.dropna()

print(new_df.to_string())

#Notice in the result that some rows have been removed (row 18, 22 and 28).

#These rows had cells with empty values.

OUTPUT:-
# Program handle wrong data where value is greater than 120 of duration set
that value = 120

import pandas as pd

df = pd.read_csv('data.csv')

for x in df.index:
if df.loc[x, "Duration"] > 120:
df.loc[x, "Duration"] = 120

print(df.to_string())

OUTPUT:-
# Program of handling duplicate values in data frame

import pandas as pd

df = pd.read_csv('data.csv')

df.drop_duplicates(inplace = True)

print(df.to_string())

#Notice that row 12 has been removed from the result

OUTPUT:-
# Program to find correlation between columns

import pandas as pd

df = pd.read_csv('data.csv')

print(df.corr())

OUTPUT:-
# Program to remove all rows with NULL values
import pandas as pd

df = pd.read_csv('data.csv')

df.dropna(inplace = True)

print(df.to_string())

OUTPUT:-
# Program of slicing by row and column

import pandas as pd

data = [[50, True], [40, False], [30, False]]


label_rows = ["Sally", "Mary", "John"]
label_cols = ["age", "qualified"]

df = pd.DataFrame(data, label_rows, label_cols)


print(df)

print("values after slicing",df.loc["Mary", "age"])

OUTPUT:-
# Program of selection condition

pandas as pd

data = {
"age": [50, 40, 30, 40, 20, 10, 30],
"qualified": [True, False, False, False, False, True, True]
}
df = pd.DataFrame(data)
print(df)

newdf = df.where(df["age"] > 30)

print("new data frame after condition true")


print(newdf)

OUTPUT:-

import sys
# Program use of matplotlib by creating a chart
import matplotlib
import numpy as np
import matplotlib.pyplot as plt

x = np.array([2007,2008,2009,2010,2011,2012,2013])
y = np.array([450,540,1000,1050,700,1200,1000])
plt.plot(x, y)
plt.xlabel("years")
plt.ylabel("No. of students")
plt.show()
#Two lines to make our compiler able to draw:
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

OUTPUT:-
# Program of creating subplots

import matplotlib.pyplot as plt


import numpy as np

#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])

plt.subplot(1, 2, 1)
plt.plot(x,y)

#plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])

plt.subplot(1, 2, 2)
plt.plot(x,y)

plt.show()

OUTPUT:-
# Program of Scatter plots
import matplotlib.pyplot as plt
import numpy as np

x = np.array([55,75,85,75,200,117,200,95,59,110,120,90,60])
y = np.array([99,86,87,88,89,86,91,87,94,78,77,85,86])
colors = np.array([0, 10, 20, 30, 40, 45, 50, 55, 60, 70, 80, 90, 100])

plt.scatter(x, y, c=colors, cmap='viridis')


plt.xlabel("no of student")
plt.ylabel("pass percentage")
plt.show()

OUTPUT:-
# Program of creating data visualization by bar chart

import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
x = ["APPLES", "BANANAS","ORANGE","MANGO","GRAPS"]
y = [67, 78,45,89,85]
plt.bar(x, y,color="pink",width=0.3)
plt.xlabel("Name Fruits")
plt.ylabel("Percentage of people like ")
plt.show()
plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

OUTPUT:-
# Program of draw Histogram

import sys
import matplotlib

import matplotlib.pyplot as plt


import numpy as np

x = np.random.normal(150, 30, 250)

plt.hist(x,color="green")
plt.xlabel("Marks")
plt.ylabel("Percentage")
plt.show()

#Two lines to make our compiler able to draw:


plt.savefig(sys.stdout.buffer)
sys.stdout.flush()

OUTPUT:-
# Program of box plot

# Import libraries
import matplotlib.pyplot as plt
import numpy as np

# Creating dataset
np.random.seed(10)
data = np.random.normal(100, 20, 200)

fig = plt.figure(figsize =(7, 5))

# Creating plot
plt.boxplot(data)
plt.xlabel("Data")
plt.ylabel("Result")

# show plot
plt.show()

OUTPUT:-
# Create More than one Boxplot on different datasets

import matplotlib.pyplot as plt


import numpy as np

# Creating dataset
np.random.seed(10)
data_1 = np.random.normal(100, 10, 200)
data_2 = np.random.normal(90, 20, 200)
data_3 = np.random.normal(80, 30, 200)
data_4 = np.random.normal(70, 40, 200)
data = [data_1, data_2, data_3, data_4]

fig = plt.figure(figsize =(7, 5))


ax = fig.add_subplot(111)

# Creating axes instance


bp = ax.boxplot(data, patch_artist = True,
notch ='True', vert = 0)

colors = ['#0000FF', '#00FF00',


'#FFFF00', '#FF00FF']

for patch, color in zip(bp['boxes'], colors):


patch.set_facecolor(color)

# changing color and linewidth of


# whiskers
for whisker in bp['whiskers']:
whisker.set(color ='#8B008B',
linewidth = 1.5,
linestyle =":")

# changing color and linewidth of


# caps
for cap in bp['caps']:
cap.set(color ='#8B008B',
linewidth = 2)

# changing color and linewidth of


# medians
for median in bp['medians']:
median.set(color ='red',
linewidth = 3)

# changing style of fliers


for flier in bp['fliers']:
flier.set(marker ='D',
color ='#e7298a',
alpha = 0.5)

# x-axis labels
ax.set_yticklabels(['data_1', 'data_2',
'data_3', 'data_4'])

# Adding title
plt.title("Malwa college Data")
plt.xlabel("student marks")
plt.ylabel("Percentage")

# Removing top axes and right axes


# ticks
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()

# show plot
plt.show()

OUTPUT:-

You might also like