0% found this document useful (0 votes)
27 views15 pages

Python Programming

Python Programming

Uploaded by

aryanshinde3002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views15 pages

Python Programming

Python Programming

Uploaded by

aryanshinde3002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Python Programming

Functions in math module


ceil() function :->

>>a=3.56

>>math.ceil(a)

if this function used then it returns value greater than the number which is present inside the ()

For example :-

>> print(math.ceil(3.56))

Output >> 4

floor() function :->

>>a=3.56

>>math.floor(a)

If we use this function then it returns value smaller than the number which is present inside the ()

For example :-

>>print(math.floor(3.56))

Output >>3

sqrt() function :->

>>math.sqrt(9)

If this function is used then it returns square root of the number present inside the ()

For example :-

>>print(math.sqrt(9))

Output >> 3

Square root of 9 is 3

trunc() function :->

>>math.trunc(3.45)

It returns truncated part of integer parts of a number

For example :-

>>print(math.trunc(3.46))

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Output >> 3

If the 3.46 number is truncated then .46 is deleted and 3 number is displayed

Numpy Package
Program 1

import numpy as np
a = np.array([10,20,30])
print(a)

Program 2

import numpy as np
mylist = [10,20,30,40]
arr = np.array(mylist)

print("Array : ",arr)
print("Datatype : ",arr.dtype)
print("Dimension : ",arr.ndim)
print("Shape : ",arr.shape)

Program 3

import numpy as np

mylist = [[10,20],[30,40]]
matrix = np.array(mylist)

print(matrix)

Program 4

import numpy as np

mylist = [[10,20],[30,40]]
matrix = np.array(mylist)

print(matrix)
print("Datatype : ",matrix.dtype)
print("Dimension : ",matrix.ndim)
print("Shape : ",matrix.shape)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Program to display message
>>> print("Welcome To Python Programming")

>>> print(“Hello, MSBTE”)

Input Method
Input Method is used to take input from user or through keyboard.

>>> a = input(“Enter a number = “)

Write a Python program to find the square root of a given number

print("Enter the number:")


num =float(input())
result=num**0.5
print("The sqaure root of "num," is ",result)

Output :-

Enter the number:


25
The square root of 25.0 is 5.0
>>>

Write a program in Python to print area and perimeter of a circle.

r=10
PI = 3.14
area= PI*r*r
perimeter= 2.0*PI*r
print("Area of Circle = ",area);
print("Perimeter of Circle = ",perimeter)

Write a program to convert Fahrenheit to Celsius.

f=95.5
c= (f-32)/1.8
print("Celsius = ",c)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a Python program to check whether the given number is even or odd.

print ("Enter value of n")


n=int (input ())
if n%2==0:
print ("Even Number")
if n%2==1:
print ("Odd Number")

Write a python program to display the result such as distinction, first class, second class, pass or fail
based on the marks entered by the user.

print("Enter your marks")


m=int(input())
if m >= 75:
print("Grade = Distinction")
elif m>=60:
print("Grade = First Class")
elif m >= 50:
print("Grade = Second Class")
elif m >= 40:
print("Grade = Pass Class")
else:
print("Grade = Fail")

Write a program to find square of number

no=int(input("Enter num = "))


sq=no*no
print("Square of ",no," = ",sq)

Write a program to find square root of number by importing math package.

import math as m
x=float(input("Enter a number = "))
a=m.sqrt(x)
print("Square root of ",x," = ",a)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a program to convert bits to Megabyte, Gigabyte and Terabyte

def convert_bits(bits):

bits_in_megabyte = 8 * 1024 * 1024


bits_in_gigabyte = bits_in_megabyte * 1024
bits_in_terabyte = bits_in_gigabyte * 1024

mb = bits / bits_in_megabyte
gb = bits / bits_in_gigabyte
tb = bits / bits_in_terabyte

return mb, gb, tb

bits = 10000000000
mb, gb, tb = convert_bits(bits)

print(f"{bits} bits is:")


print(f"{mb} MB")
print(f"{gb} GB")
print(f"{tb} TB")

Write a program for swapping of two numbers

def swap_values(a, b):


a, b = b, a
return a, b

x = 10
y = 20
print("Before Swap: x = ",x," y = ",y)
x, y = swap_values(x, y)
print("After Swap: x = ",x," y = ",y)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a program to check the largest number among the three numbers

a=10
b=40
c=30

if a>b :
print(a," is largest number")
else:
if b>c :
print(b," is largest number")
else:
print(c," is largest number")

Write a program to check whether is positive, negative or zero

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

if a>0 :
print("Number is Positive")
elif a<0 :
print("Number is Negative")
else:
print("Number is Zero")

Write a program to print all even numbers between 1 to 100

print("Even numbers from 1 to 100 = ")


for i in range(1,101):
if i%2==0 :
print(i)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a program to print all even numbers between 1 to 100 using while loop

a=1
print("even numbers from 1 to 100 = ")
while a!=101:
if a%2==0 :
print(a)
a=a+1

Write a python program to find Fibonacci series for given number

n=int(input("Enter a number = "))


a=0
b=1
for i in range(1,n+1):
if a==0 :
print(f"Fibonacci series = {a} {b}",end=" ")
c=a+b
a=b
b=c
print(c,end=" ")

Write a program to swap the value of two variables.

a = input("Enter the value of a: ")


b = input("Enter the value of b: ")

print("Before swapping: a = ",a," b = ",b)

c=a
a=b
b=c

print("After swapping: a = ",a," b = ",b)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a program to calculate surface volume and area of a cylinder.

import math

def cylinder_volume(radius, height):


return math.pi * (radius**2) * height

def cylinder_surface_area(radius, height):


return 2 * math.pi * radius * (radius + height)

print("Cylinder Calculator")
r = float(input("Enter the radius of the cylinder: "))
h = float(input("Enter the height of the cylinder: "))

volume = cylinder_volume(r,h)
sarea = cylinder_surface_area(r,h)

print(f"Volume of the cylinder: {volume}")


print(f"Surface area of the cylinder: {sarea}")

Write a program to check if the input year is leap year or not.

year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):


print(year," is a leap year.")
else:
print(year," is not a leap year.")

Write a program that takes the marks of 5 subjects and displays the grades.

subjects = []
for i in range(1,6):
a=int(input(f"Enter marks for subject {i} = "))
subjects.append(a)

total = sum(subjects)
average = total / 5

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


if average >= 75:
print("Grade = A")
elif average >= 60:
print("Grade = B")
elif average >= 50:
print("Grade = C")
elif average >= 40:
print("Grade = D")
else:
print("Grade = Fail")

Write a python program to find sum of four digit number.

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


num1=num
sum=0
for i in range(1,5):
remain=num1%10
sum=sum+remain
num1=num1//10

print("sum of given num = ",sum)

Write a Python program to find common items from two lists.

list1 = [10,20,30,40,50,60]
list2 = [20,40,60,80]
list3=[]

for x in list1:
for y in list2:
if x==y :
list3.append(x)

print("Common items = ",list3)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Create a tuple and find the minimum and maximum number from it.

tup1=(10,20,30,40,50)
print("Maximum number is ",max(tup1))
print("Minimum number is ",min(tup1))

Write a Python program to find the repeated items of a tuple.

from collections import Counter

tuple = (1, 2, 3, 4, 5, 2, 3, 6, 7, 3, 8, 2)

count = Counter(tuple)
repeated={}

for key, value in count.items():


if value > 1:
repeated[key] = value

print("Repeated items in the tuple with their counts:")

for item, count in repeated.items():


print(f"{item}: {count}")

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a Python Script to concatenate following dictionaries to create a new one.

Sample Dictionary: dic1 = {1:10, 2:20} dic2 = {3:30, 4:40} dic3 = {5:50,6:60}

dic1 = {1:10, 2:20}


dic2 = {3:30, 4:40}
dic3 = {5:50,6:60}
dict4={}

for key,item in dic1.items():


dict4[key]=item

for key,item in dic2.items():


dict4[key]=item

for key,item in dic3.items():


dict4[key]=item
print(dict4)

Write a Python program to combine two dictionary adding values for common keys.

d1 = {'a': 100, 'b': 200, 'c':300} d2 = {'a': 300, 'b': 200, 'd':400}

d1 = {'a': 100, 'b': 200, 'c':300}


d2 = {'a': 300, 'b': 200, 'd':400}

d3 = {}

for key,item in d1.items():


d3[key]=item

for key,item in d2.items():


d3[key]=item

print("d3 = ",d3)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a Python program to create two matrices and perform addition, subtraction, multiplication and
division operation on matrix using NumPy.

import numpy as np

x=np.array([[1,2],[4,5]])
y=np.array([[6,7],[8,10]])

print("Element wise addition =")


print(np.add(x,y))

print("Element wise subtraction =")


print(np.subtract(x,y))

print("Element wise Multiplication =")


print(np.multiply(x,y))

print("Element wise Division =")


print(np.divide(x,y))

Write a python program to concatenate two strings using NumPy.

import numpy as np

x1 = np.array(['Hello ', 'Good '], dtype=np.str_)


x2 = np.array(['World', 'Morning'], dtype=np.str_)

result = np.char.add(x1, x2)

print("Concatenated Result:", result)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a Python Class to reverse a string word by word

class Reverse:
def __init__(self, s):
self.s = s

def reverse_words(self):
return ' '.join(self.s.split()[::-1])

s = Reverse("Study for Buddy")

reversed_words = s.reverse_words()

print(reversed_words)

Write a Python class named Rectangle constructed from length and width and a method that will
compute the area of a rectangle.

class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
self.area = self.length * self.width
return self.area

a=int(input("Enter length of rectangle: "))


b=int(input("Enter width of rectangle: "))
r = Rectangle(a,b)

print("Area of Rectangle = ",r.area())

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


Write a Python program to create a class to print the area of a square and a rectangle. The class has two
methods with the same name but different number of parameters. The method for printing area of
rectangle has two parameters which are length and breadth respectively while the other method for
printing area of square has one parameter which is side of square.

class SquareRect:
def area(self, *args):
if len(args) == 1:
side = args[0]
print("Area of Square = ", side * side)
elif len(args) == 2:
length, width = args
print("Area of Rectangle = ", length * width)
else:
print("Invalid number of arguments")

sqr = SquareRect()

sqr.area(5)
sqr.area(5, 10)

Write a Python program to create a class 'Degree' having a method 'getDegree' that prints "I got a
degree". It has two subclasses namely 'Undergraduate' and Postgraduate' each having a method with
the same name that prints "I am an Undergraduate" and "I am a Postgraduate" respectively. Call the
method by creating an object of each of the three classes.

class Degree:
def getDegree(self):
print("I got a degree")

class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")

class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")

degree = Degree()
undergraduate = Undergraduate()
postgraduate = Postgraduate()

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER


degree.getDegree()
undergraduate.getDegree()
postgraduate.getDegree()

Write a Python program to create series from array using Panda.

import pandas as pd
import numpy as np
array = np.array([10, 20, 30, 40, 50])
series = pd.Series(array)
print("Pandas Series:")
print(series)

PYTHON PROGRAM CODES PYTHON CHEAT SHEET 4TH SEMESTER

You might also like