Python Programming
Introduction to python programming
Python is a high-level, interpreted programming language known for its simplicity and versatility. It is widely used in various fields, from web development to data science, machine learning, automation, and more. This introduction will cover the basics of Python programming, including its features, installation, and core concepts.
write a python program to demonstrate basic data types in python (here we have many other data types)
sol:
print("----int----")
print("possible integer values")
print(15)
print(-25)
print(0o15)
print(0x12a)
x=2
x=int(2)
print(x)
print(int(25.5))
print(int("25"))
print("operations on integers")
print("arithmetic operatons")
print(2**3)
print(2*3)
print(20/3)
print(10//3)
print(10+3)
print(10-3)
print("mathematical function")
print(pow(2,3))
print(divmod(10,3))
print("Bitwise operators")
print(2&3)
print(2/3)
print(2^3)
print(~2)
print(2<<3)
print(2>>3)
print("Relational operators")
print(10<3)
print(10>=3)
print(10!=3)
print("---float---")
print("possible values with decimal point or e/E")
print(10.5)
print(0.000000009)
print("mathematical funcions")
print(pow(1.2,0.1))
print(abs(-2.5))
print(round(2.3))
print("---complex---")
print(2+3j)
print(complex(2,3))
print(abs(3+4j))
print(complex(2))
print("---str---")
print("hello world","from","\'india\'")
print("""hello "world" from 'india""")
print(str("10"))
print('aBc'.upper)
print('hello world'.capitalize())
print('hello world'.swapcase())
print("hello"+"world")
print("----bool-----")
x=True
print(x)
x=bool(True)
print(x)
print(bool())
print(bool(0))
print(bool(25))
print(bool(-12.5))
print(bool("hello"))
print("operaions on bool type:and not or")
print(2&5)
print(5&2)
print(2 or 5)
print(5 or 2)
print(not 2)
print(not 0)
Program 2:
Write a python program to create a list and perform the following methods
a.insert() b.remove() c.append() d.len() e.pop() f.clear()
print("---list creation[]---")
fruits=list(['apple','mango','cherry'])
fruits=['apple','mango','cherry']
print(fruits[0])
print(fruits[-1])
for i in fruits:print(i)
print("----insertion at position i : list.insert(i,x)----")
fruits.insert(2,"banana")
fruits.insert(2,"pear")
fruits.insert(2,"berry")
fruits.insert(2,"grape")
print(fruits)
print("---removal---")
fruits.remove("cherry")
print(fruits)
del fruits[0]
print(fruits)
del fruits[1:5:2]
print(fruits)
print(fruits.pop())
print("----appending---")
fruits.append("orange")
print(fruits)
fruits2=["guava","plum"]
fruits.extend(fruits2)
print(fruits)
print("----length----")
print(len(fruits))
print("----pop()----")
fruits.pop()
fruits.pop(2)
print(fruits)
fruits.clear()
print(fruits)
output:
Program 3:
Write a python program to create a tuple and perform the following methods
a.add items() b.len() c.check for an item in a tuple() d.access items()
print("----Tuple Creaton----")
x=(4,6,2,8,3,1)
y=tuple([10,50,60,40,80,70,90,23,45,67])
print(y)
print("---add itema to tuple---")
x=x+(9,7)
print(x)
x=x[:3]+(15,20)
print(x)
listx=list(x)
listx.append(30)
print(list)
x=tuple(listx)
print(x)
print("---length of tuple---")
print(len(x))
print("---search element in tuple---")
print(2 in x)
inp=int(input("Enter a value to search"))
print(int(inp)in x)
print(x.index(inp))
print("---access items from tuple---")
print(x[1:3])
output:
Program 4:
Write a python program to createa a Dictionary and apply the following methods
a.print the dictionary items() b.access items() c.use get() d.change value() e.len()
print("---Dictionay Creation---")
D=dict({'Apple':'Red','Grapes':'Green','Banana':'yellow'})
print(D)
D=dict([('Apple','Red'),('Grapes','Green'),('Banana','yellow')])
print(D)
D={'Apple':'Red','Grapes':'Green','Banana':'yellow'}
print(D)
print("-----Print the dictionay items-----")
for f in D:
print(D)
for f in D:
print(D[f])
for k,v in D.items():
print(k,v)
print("----Access dictionry items-----")
print(D['Apple'])
k='Banana'
print(D[k])
print("----get()method----")
k='Gauva'
print(D.get(k))
print("---Change Dictionary items---")
D['Plums']='Brown'
print(D)
D['Plums']='Red'
print(D)
print("---Length of the Dictionary---")
print(len(D))
D={}
print(len(D))
output:
Program 5:
Write a program to create a Menu with the following options
a.Additon b.Subtraction c.Multiplicaiton d.Divison
1
#Learnprogramo - programming made simple
# defining addition function
def add(a, b):
sum = a + b
print(a, "+", b, "=", sum)
# defining subtraction function
def subtract(a, b):
difference = a - b
print(a, "-", b, "=", difference)
# defining multiplication function
def multiply(a, b):
product = a * b
print(a, "x", b, "=", product)
# defining division function
def divide(a, b):
division = a / b
print(a, "/", b, "=", division)
# printing the heading
print("WELCOME TO A SIMPLE CALCULATOR")
# using the while loop to print menu list
while True:
print("\nMENU")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = int(input("\nEnter the Choice: "))
# using if-elif-else statement to pick different options
if choice == 1:
print( "\nADDITION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
add(a, b)
elif choice == 2:
print( "\nSUBTRACTION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
subtract(a, b)
elif choice == 3:
print( "\nMULTIPLICATION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
multiply(a, b)
elif choice == 4:
print( "\nDIVISION\n")
a = int( input("First Number: "))
b = int( input("Second Number: "))
divide(a, b)
elif choice == 5:
break
else:
print( "Please Provide a valid Input!")
output:
Program 6:
Write a python program to print A number is positive/negative using if-else
n=float(input("Enter a number:"))
if n > 0:
print("You have entered a positive number")
elif n==0:
print("You have entered Zero")
else:
print("You have entered a negative number")
output:
Program 7:
Write a python program using filter() to filter only even number from a given list
L1=[1,6,4,9,7,0,8,3]
def f(x):return x%2==0
M=list(filter(f,L1))
print("Origianl List:",L1)
print("Filtered List:",M)
output:
Program 8:
Write a python program to print date, time for today and now
from datetime import datetime
now = datetime.now()
print("Now=",now)
dt_string=now.strftime("%d/%m/%y %H:%M:%S")
print("Date and Time=",dt_string)
output:
Program 9: Write a python program to add some days to your present date and print the date added
from datetime import date
today =date.today()
dte=today.strftime("%b %d,%Y")
print("current date:",dte)
from datetime import datetime, timedelta
days=int(input("How many days to add?"))
dteadd=datetime.now()+timedelta(days)
dteaddf=dteadd.strftime("%b %d,%Y")
print("Date after adding"+str(days)+"days:"+str(dteaddf))
output:

Program 10: Write a program to count the number of characters in the string and store them in a dictionay data structure
n=input("Enter a string:")
s={}
for i in n:
if i in s:
s[i]+=1
else:
s[i]=1
print(s)
output:
Program 11: Write a program to count frequency of characters in a given file
and here you need to create a python.txt file and add some data
def char_frequency(str1):
dict={}
for n in str1:
keys=dict.keys()
if n in keys:
dict[n]+=1
else:
dict[n]=1
return dict
str = input("Enter python.txt to read from:")
getfile=open(str).read()
D=char_frequency(getfile)
print("The frequency of each charcter in the file")
for k,v in D.items():
print(k,v)
output:
Program 12:Using a numpy module create an array and check the following:
1. Type of array 2. Axes of array 3. Shape
of array 4. Type of elements in array
import numpy as np
arr = np.array([[1,2,3,],[4,2,5]])
print("Array is of type:",type(arr))
print("No. of dimensions.",arr.ndim)
print("Shape of the array:",arr.shape)
print("Size of the arry:",arr.size)
output:
Program 13:Write a python program to concatenate the dataframes with two different objects
import pandas as pd
data1 = pd.DataFrame({'Regno':['101','102','103','104'],'Comp':['77','66','80','40'],
'Maths':['88','55','90','50'],})
data2 = pd.DataFrame({'Regno':['201','202','203','204','205'],'Comp':['77','60','80','90','80'],
'Maths':['88','60','76','56','76'],})
print("original DataFrames")
print(data1)
print("-------------------------------")
print(data2)
print("\nConcatenate two dataframes with different columns:")
result=pd.concat([data1,data2],axis=0,ignore_index=True)
print(result)
output:
Program14:Write a python code to read a csv file using pandas module and print the first and last five lines of a file [here guys we have to download a csv file form browser or you can create a csv files {https://people.sc.fsu.edu/~jburkardt/data/csv/} here is the link you can download open the link and go to cities link and open it and download the files]
import pandas as pd
df = pd.read_csv('enter the location of your cities.csv file')
print("First 5 lines:")
print(df.head())
print("Last 5 lines:")
print(df.tail())
output:
Program15:Write a python program which accepts the radius of a circle from user and computes the area (use math
module)
from math import pi
r = float(input("Enter the radius of the circle:"))
print("The area of the circle with radius:"+str(pi*r*2))
output:
Program16(a):Get total profit of all months and show line plot with the following Style properties
Generated line plot must include following Style properties: –
create the below table in excel sheet and save it as store.csv
Line Style dotted and Line-color should be blue
• Show legend at the lower right location
• X label name = Months
• Y label name = Sold units
• Line width should be 4
import pandas as pd
import matplotlib.pylab as plt
df = pd.read_csv("Store.csv")
profitList = df['Total Profit'].tolist()
monthList = df['Months'].tolist()
plt.plot(monthList,profitList,label = 'Profit Details', color='b',marker='o',
markerfacecolor='k',linestyle='--',linewidth=4)
plt.xlabel('Months')
plt.ylabel('Sold Units')
plt.legend(loc='lower right')
plt.title("Sales Details")
plt.show()
output:
(b):Display the number of units sold per month for each product using multiline plots. (i.e., Separate
Plotline for each product)
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("Store.csv")
monthList = df['Months'].tolist()
y1 = df['Pen'].tolist()
y2 = df['Book'].tolist()
y3 = df['Marker'].tolist()
y4 = df['Chair'].tolist()
y5 = df['Table'].tolist()
y6 = df['Pen Stand'].tolist()
plt.plot(monthList,y1,label='Pen',Marker='o',linewidth=3)
plt.plot(monthList,y2,label='Book',Marker='*',linewidth=3)
plt.plot(monthList,y3,label='Marker',Marker='o',linewidth=3)
plt.plot(monthList,y4,label='Chair',Marker='*',linewidth=3)
plt.plot(monthList,y1,label='Table',Marker='0',linewidth=3)
plt.plot(monthList,y1,label='Pen stand',Marker='*',linewidth=3)
plt.xlabel('Month number')
plt.ylabel('Sales Units in number')
plt.legend(loc='upper left')
plt.xticks(monthList)
plt.yticks([500,1000,2000,4000,6000,8000,10000,12000,15000])
plt.title('sales data')
plt.show()
output:
(c):Read chair and table product sales data and show it using the bar chart.
• The bar chart should display the number of units sold per month for each product. Add a
separate bar for each product in the same chart.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('enter the location of your store.csv file')
monthList = df['Months'].tolist()
y1 = df['Chair'].tolist()
y2 = df['Table'].tolist()
plt.bar([a-0.25 for a in monthList], y1, width= 0.25, label='Chair',align='edge')
plt.bar([a+0.25 for a in monthList], y2, width= -0.25, label='Table',align='edge')
plt.xlabel('Month Number')
plt.ylabel('Sales units in number')
plt.legend(loc='upper left')
plt.title('Sales data')
plt.xticks(monthList)
plt.grid(True, linewidth=1, linestyle="--")
plt.title('Chair & Table Sales')
plt.show()
output:
(d):Read all product sales data and show it using the stack plot
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('/enter the location of your store.csv file')
monthList = df = ['Months'].tolist()
y1 = df ['Pen'].tolist()
y2 = df ['Book'].tolist()
y3 = df ['Marker'].tolist()
y4 = df ['Chair'].tolist()
y5 = df ['Table'].tolist()
y6 = df ['Pen stand'].tolist()
plt.plot([],[],color='m',lable='Pen',linewidth=5)
plt.plot([],[],color='c',lable='Book',linewidth=5)
plt.plot([],[],color='r',lable='Marker',linewidth=5)
plt.plot([],[],color='k',lable='Chair',linewidth=5)
plt.plot([],[],color='g',lable='Table',linewidth=5)
plt.plot([],[],color='y',lable='Pen stand',linewidth=5)
plt.stackplot(monthList,y1,y2,y3,y4,y5,y6,colors=['m','c','r','k','g','y'])
plt.xlabel('Month Number')
plt.ylabel('Sales Unints in Number')
plt.title('All product sales data using Stack Plot')
plt.legend(loc='upper left')
plt.show()
output:
Here are the final programs if you find any difficult contact me for any kind of queries this are the programs of bca nep 3rd sem
Comments
Post a Comment