0% found this document useful (0 votes)
15 views20 pages

Python Lab

Uploaded by

ramramchandu05
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
15 views20 pages

Python Lab

Uploaded by

ramramchandu05
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 20

PYTHON PROGRAMMING LAB

1a. Write and execute simple python Program.

Source Code:

# This program prints Hello, world!

print('Hello, world!')

1b. Write and execute simple python Program to add two numbers?

Source Code:

a=int(input("enter a number:"))

b=int(input("enter a number:"))

c=a+b

print("addition of two numbers:",c)

1c.To Write A Simple Program To Swap Two Numbers?

Source Code:

x = input('Enter value of x: ')

y = input('Enter value of y: ')

# create a temporary variable and swap the values

temp = x

x=y

y = temp

print('The value of x after swapping:',x)

print('The value of y after swapping:',y)


1d. To write a simple program to print area of triangle?

Source code:

# Three sides of the triangle is a, b and c:

a = float(input('Enter first side: '))

b = float(input('Enter second side: '))

c = float(input('Enter third side: '))

# calculate the semi-perimeter

s = (a + b + c) / 2

# calculate the area

area = (s*(s-a)*(s-b)*(s-c)) ** 0.5

print('The area of the triangle is:',area)

2.To write a python program to demonstrate list and dictionary?

Source code:

#LIST

list1=[1,"hi","python",2]

print(type(list1))

print(list1)

print(list1[3:])

print(list1[0:2])

print(list1*3)

#Dictionary

d={1:"jimmy", 2:"alex", 3:"john",4:"mike"}

print(d)

print("1st name is:", d[1])


print("1st name is:",d[4])

print(d.keys())

print(d.values())

3 a. Write /execute simple ‘Python’ program to demonstrate type conversion using int and
float data type ?

Source Code:

a = "10010"

b = int(a,2)

print ("following the conversion to integer base 2:")

print (b)

d = float(a)

print ("After converting to float : ")

print (d)

3 b. write a python program on arithmetic operators?

Source code:

a=7

b=2

# addition

print ('Sum: ', a + b)

# subtraction

print ('Subtraction: ', a - b)

# multiplication

print ('Multiplication: ', a * b)

# division
print ('Division: ', a / b)

# floor division

print ('Floor Division: ', a // b)

# modulo

print ('Modulo: ', a % b)

# a to the power b

print ('Power: ', a ** b)

4a. Write simple programs to convert U.S. dollars to Indian rupees.

Source code:

dollar = int (input("Enter the amount in dollars: $"))

rs = dollar*81.98500

print("Converted amount in rupees is: ",rs)

4b. Write simple programs to convert bits to Megabytes, Gigabytes and Terabytes.

Source code:

B=float(input("enter a bit:"))

KB=B/1024

MB=B/(1024*1024)

GB=B/(1024*1024*1024)

TB=B/(1024*1024*1024*1024)

print(B,"KILOBYTE IS:",KB)

print(B,"MEGABYTE IS:",MB)

print(B,"GIGABYTE IS:",GB)

print(B,"TERABYTE IS:",TB)
5. Write simple programs to calculate the area and perimeter of the square, and the
volume & Perimeter of the cone.

Source code:

side = int (input ("Enter the side of a square: " ))

area = side*side #Formula for Area of square

perimeter = 4*side #Formula for Perimeter of square

print("Area of a square : ",area)

print("Perimeter of a square : ",perimeter)

height=38

radius=35

pie=3.14285714286

volume=pie*(radius*radius)*height/3

print("volume of the cone=",(volume))

6a. Write program to determine whether a given number is odd or even.

Source code:

num = int(input("Enter a Number:"))

if num % 2 == 0:

print(num ,"Given number is Even:")

else:

print(num ,"Given number is Odd")


6 b. Write program to Find the greatest of the three numbers using conditional operators.

Source code:

num1 = int(input("Enter a Number:"))

num2= int(input("Enter a Number:"))

num3= int(input("Enter a Number:"))

if (num1> num2) and (num2> num3) :

largest = num1

elif (num2 > num1) and (num2>num3) :

largest = num2

else :

largest = num3

print(largest, "is the largest of three numbers.")

7 a. Write a program to Find factorial of a given number.

Source code:

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

fact=1

if n < 0:

print("Factorial does not exist for negative numbers")

elif n == 0:

print("The factorial of 0 is 1")

else:

for i in range(1, n + 1):

fact = fact * i

print("The factorial of",n,"is",fact)


7 b. Write a python program to Generate multiplication table up to 10 for numbers 1 to 5

Source code:

for i in range(1,11):

print("\n\nMULTIPLICATION TABLE FOR %d\n" %(i))

for j in range(1,11):

print("%-5d X %5d = %5d" % (i, j, i*j))

8 a. Write a Python program to Find factorial of a given number using recursion.

Source code:

#Factorial of a number using recursion

def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

num =int(input("enter a number:"))

# check if the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of", num, "is", recur_factorial(num))


8 b. Write a Python program to Generate Fibonacci sequence up to 100 using recursion

Source code:

def fibonnaci(n):

if n <= 1:

return n

else:

return(fibonnaci(n-1) + fibonnaci(n-2))

nterms = int(input("How many terms? "))

for i in range(nterms):

print(fibonnaci(i))

9 a. Write a python program to Create a list?

Source code:

# Python program to demonstrate

# Creating a List

List = []

print("Blank List: ")

print(List)

# Creating a List of numbers

List = [10, 20, 14]

print("\nList of numbers: ")

print(List)

# Creating a List of strings and accessing

# using index

List = ["HI", "Hello", "Python"]


print("\n List Items: ")

print(List[0])

print(List[2])

# Creating a List with

# the use of Numbers

# (Having duplicate values)

List = [1, 2, 4, 4, 3, 3, 3, 6, 5]

print("\nList with the use of Numbers: ")

print(List)

# Creating a List with

# mixed type of values

# (Having numbers and strings)

List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks']

print("\nList with the use of Mixed Values: ")

print(List)

9 b. Write a python program to add elements to the list?

Source code:

# Python program to demonstrate

# Addition of elements in a List

# Creating a List

List = []

print("Initial blank List: ")

print(List)

# Addition of Elements
# in the List

List.append(1)

List.append(2)

List.append(4)

print("\nList after Addition of Three elements: ")

print(List)

# Adding Tuples to the List

List.append((5, 6))

print("\nList after Addition of a Tuple: ")

print(List)

# Addition of List to a List

List2 = ['hello', 'python']

List.append(List2)

print("\nList after Addition of a List: ")

print(List)

9 c. Write a python program to delete elements to the list?

Source code:

#remove method

l = [1, 4, 6, 2, 6, 1]

print("List before calling remove function:")

print(l)

l.remove(6)

print("List after calling remove function:")

print(l)
#del method

l = [1, 4, 6, 2, 6, 1]

print("List before calling del:")

print(l)

del l[3]

print("List after calling del:")

print(l)

#pop method

l = [1, 4, 6, 2, 6, 1]

print("List before calling pop function:")

print(l)

print(l.pop(4))

print("List after calling pop function:")

print(l)

10. Write a python program to Sort the list, reverse the list and counting elements in a list.

Source code:

# create a list of prime numbers

prime_numbers = [2, 3, 5, 7,7]

# reverse the order of list elements

prime_numbers.reverse()

print('Reversed List:', prime_numbers)

# sort the list in ascending order

prime_numbers.sort()

print(prime_numbers)
#count

print(prime_numbers.count(7))

11 a.Write a python program to Create dictionary?

Source code:

#Creating a Dictionary

# Initializing a dictionary with some elements

Dictionary = {1: 'Javatpoint', 2: 'Python', 3: 'Dictionary'}

print("\nDictionary created using curly braces: ")

print(Dictionary)

# Creating a Dictionary with keys of different data types

Dictionary = {'java': 'python', 3: [2, 3, 5, 'Dictionary']}

print("\nDictionary with keys of multiple data type: ")

print(Dictionary)

11 b. Write a python program to add element to the dictionary?

Source code:

# Initializing an empty Dictionary

Dictionary = {}

print("The empty Dictionary: ")

print(Dictionary)

# Inserting key:value pairs one at a time

Dictionary[0] = 'ptrhon'

Dictionary[2] = 'java'

Dictionary.update({ 3 : 'Dictionary'})

print("\nDictionary after addition of these elements: ")


print(Dictionary)

# Adding a list of values to a single key

Dictionary['list_values'] = 3, 4, 6

print("\nDictionary after addition of the list: ")

print(Dictionary)

# Updating values of an already existing Key

Dictionary[2] = 'WT'

print("\nUpdated dictionary: ")

print(Dictionary)

# Adding a nested Key to our dictionary

Dictionary[5] = {'Nested_key' :{1 : 'Nested', 2 : 'Key'}}

print("\nAfter addtion of a Nested Key: ")

print(Dictionary)

11 c. Write a python program to delete element to the dictionary?

Source code:

#using del keyword

my_dict = {31: 'a', 21: 'b', 14: 'c'}

del my_dict[31]

print(my_dict)

#using pop

my_dict = {31: 'a', 21: 'b', 14: 'c'}

print(my_dict.pop(31))

print(my_dict)

# clear method
numbers = {1: "one", 2: "two"}

numbers.clear()

print(numbers)

12. Write a program to: To calculate average, mean, median of numbers in a list.

Source code:

numb=[1,2,3,6,8]

print("the given list is:", numb)

no=len(numb)

sum1=sum(numb)

mean=sum1/no

print("the mean or average value of numb is:", mean)

numb=[2,6,5,4,8]

print("tha given list is:", numb)

no=len(numb)

numb.sort()

print("the sorted list is:", numb)

median=sorted(numb)[len(numb)//2]

print("the median value of numb is:", median)

13 a) Write a python program To print Factors of a given Number.

Source code:

N = int(input("Enter the value of N: "))


x=1
while x<=N:
if N%x==0:
print(x)
x = x+1

13 b) Write a program to check whether the given number is prime or not in python.

SOURCE CODE:
num=int(input("Enter a number:"))
i=1
count=1
for i in range(1,num):
if(num%i==0):
count=count+1
if(count==2):
print("Prime number")
else:
print("not a prime number")

13 c. Write Python program to check if the number is an Armstrong number or not?

SOURCE CODE:

# 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")

13 d. write a python program to reverse a string


SOURCE CODE:
def reverse_string(str):
str1 = "" # Declaring empty string to store the reversed string
for i in str:
str1 = i + str1
return str1 # It will return the reverse string to the caller function
str = "JavaTpoint" # Given String
print("The original string is: ",str)
print("The reverse string is",reverse_string(str)) # Function call

14.File Input/output: Write a program to: i) To create simple file and write “Hello World”
in it.
ii) To open a file in write mode and append Hello world at the end of a file.

Source code:

demofile.txt

HELLO WORLD

f = open("demofile.txt", "r")

print(f.read())

f = open("demofile.txt", "a")
f.write("Now the file has more content!")

f.close()

f = open("demofile.txt", "r") #open and read the file after the appending:

print(f.read())

f = open("demofile.txt", "w")

f.write("Woops! I have deleted the content!")

f.close()

#open and read the file after the appending:

f = open("demofile.txt", "r")

print(f.read())

15. write a python Program to multiply two matrices using nested loops.
Source code:
# 3x3 matrix
X = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)

16. Write a program to Create and Access a Python Package?

Creating Packages
We have included a __init__.py, file inside a directory to tell Python that the current directory
is a package. Whenever you want to create a package, then you have to include __init__.py file
in the directory. You can write code inside or leave it as blank as your wish. It doesn't bothers
Python.
Follow the below steps to create a package in Python

 Create a directory and include a __init__.py file in it to tell Python that the current
directory is a package.
 Include other sub-packages or files you want.

 Next, access them with the valid import statements.


Let's create a simple package that has the following structure.
Package (university)

 __init__.py
 student.py

 faculty.py
Go to any directory in your laptop or desktop and create the above folder structure. After
creating the above folder structure include the following code in respective files.
Example
# student.py
class Student:

def __init__(self, student):


self.name = student['name']
self.gender = student['gender']
self.year = student['year']

def get_student_details(self):
return f"Name: {self.name}\nGender: {self.gender}\nYear: {self.year}"

# faculty.py
class Faculty:

def __init__(self, faculty):


self.name = faculty['name']
self.subject = faculty['subject']

def get_faculty_details(self):
return f"Name: {self.name}\nSubject: {self.subject}"
We have the above in the student.py and faculty.py files. Let's create another file to access
those classed inside it. Now, inside the package directory create a file named testing.py and
include the following code.
Example
# testing.py
# importing the Student and Faculty classes from respective files
from student import Student
from faculty import Faculty

# creating dicts for student and faculty


student_dict = {'name' : 'John', 'gender': 'Male', 'year': '3'}
faculty_dict = {'name': 'Emma', 'subject': 'Programming'}

# creating instances of the Student and Faculty classes


student = Student(student_dict)
faculty = Faculty(faculty_dict)
# getting and printing the student and faculty details
print(student.get_student_details())
print()
print(faculty.get_faculty_details())
If you run the testing.py file, then you will get the following result.
Output
Name: John
Gender: Male
Year: 3

Name: Emma
Subject: Programming

You might also like