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

Python Programming Lab Exercises

Uploaded by

ramramchandu05
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)
13 views20 pages

Python Programming Lab Exercises

Uploaded by

ramramchandu05
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

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)

[Link] 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)

[Link] 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([Link]())

print([Link]())

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

[Link](1)

[Link](2)

[Link](4)

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

print(List)

# Adding Tuples to the List

[Link]((5, 6))

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

print(List)

# Addition of List to a List

List2 = ['hello', 'python']

[Link](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)

[Link](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([Link](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 [Link] 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'

[Link]({ 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"}

[Link]()

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)

[Link]()

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

[Link] 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:

[Link]

HELLO WORLD

f = open("[Link]", "r")

print([Link]())

f = open("[Link]", "a")
[Link]("Now the file has more content!")

[Link]()

f = open("[Link]", "r") #open and read the file after the appending:

print([Link]())

f = open("[Link]", "w")

[Link]("Woops! I have deleted the content!")

[Link]()

#open and read the file after the appending:

f = open("[Link]", "r")

print([Link]())

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
 [Link]

 [Link]
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
# [Link]
class Student:

def __init__(self, student):


[Link] = student['name']
[Link] = student['gender']
[Link] = student['year']

def get_student_details(self):
return f"Name: {[Link]}\nGender: {[Link]}\nYear: {[Link]}"

# [Link]
class Faculty:

def __init__(self, faculty):


[Link] = faculty['name']
[Link] = faculty['subject']

def get_faculty_details(self):
return f"Name: {[Link]}\nSubject: {[Link]}"
We have the above in the [Link] and [Link] files. Let's create another file to access
those classed inside it. Now, inside the package directory create a file named [Link] and
include the following code.
Example
# [Link]
# 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 [Link] file, then you will get the following result.
Output
Name: John
Gender: Male
Year: 3

Name: Emma
Subject: Programming

Common questions

Powered by AI

Recursion is a programming technique where functions call themselves to solve sub-problems of a larger problem. In the Python program for computing factorials using recursion, the function 'recur_factorial(n)' is defined, which calls itself with the value 'n-1' until it reaches the base case where 'n' equals 1. This base case stops further recursive calls. The factorial of a number n is found by multiplying n with the factorial of (n-1) until the base case is reached, which returns 1 . This example demonstrates how recursion breaks down the factorial calculation into smaller, manageable parts.

Swapping two numbers using a temporary variable involves storing one of the numbers in a temporary storage location before assigning the values. This is demonstrated by the use of 'temp' in 'temp = x; x = y; y = temp', which temporarily holds the value of x before the values are swapped . On the other hand, tuple unpacking allows for swapping without an explicit temporary storage as values are paired and swapped in a single line, such as 'x, y = y, x'. Tuple unpacking is more concise and considered more Pythonic.

Python file I/O operations involve using open, write, read, and append methods to manipulate file content. Opening a file in 'r' (read) mode allows reading content, while 'w' (write) mode erases existing content to write new data, demonstrated by f.write('Hello World') overwriting contents . Using 'a' (append) mode appends content at the end of the file without erasing, which is efficient when you need to add data incrementally . Common pitfalls include not closing files after operations, leading to memory leaks, and overwriting important data inadvertently with 'w' mode.

Python handles data conversion between bytes and larger units such as kilobytes (KB), megabytes (MB), gigabytes (GB), and terabytes (TB) using division operations by powers of 1024. Starting with the byte value, the conversions are as follows: KB = bytes / 1024, MB = bytes / (1024*1024), GB = bytes / (1024*1024*1024), and TB = bytes / (1024*1024*1024*1024). This progression is based on the binary system where each successive unit is 1024 times larger than the previous one, reflecting the storage measures used in computing.

Lists and dictionaries are two essential data structures in Python, each suited for different tasks. Lists are ordered collections that permit duplicate elements and are indexed by position, allowing efficient iteration and element access by index . Dictionaries, however, are unordered collections that store key-value pairs, providing faster lookups and retrievals by key . Lists are used for ordered data storage and retrieval, while dictionaries are ideal for situations requiring a key-based configuration like associative arrays or mappings.

Python’s conditional operators, such as 'and', 'or', and comparison operators, are instrumental in solving problems requiring decision-making logic. For instance, to identify the greatest of three numbers, conditional operators compare pairs like 'if (num1 > num2) and (num1 > num3)', allowing the program to evaluate multiple conditions logically and assign the greatest number as the result . These operators enable comprehensive evaluations in decision trees, making them invaluable in applications ranging from data validation to complex algorithm implementations.

Type conversion in Python allows for the conversion of one data type to another, providing flexibility and interoperability between different operations. For example, converting a binary string to an integer with int(a,2) allows for arithmetic operations on the converted integer . Converting strings to floats can enable calculations involving decimal points, demonstrated by float(a) converting a string '10010' to a float . However, type conversion can introduce errors if the string format doesn't match the desired type, potentially leading to runtime exceptions. Additionally, excessive type conversion can impact performance.

Defining a custom package in Python is crucial for modular programming as it enhances code organization and reusability. A package is created by placing related modules in a directory containing an __init__.py file, marking it as a package . This allows for logical separation of code into distinct namespaces, simplifying imports and improving clarity. By structuring code into packages, developers can maintain encapsulation, reduce redundancy, and enhance collaboration through clear module interfaces and dependencies, aligning with best practices for large-scale software development.

Python offers several list modification techniques ranging in complexity and use. Adding elements can be performed using append() for single items or extend() for multiple items. Removal of elements can utilize remove(), del, or pop(), each facilitating different scenarios like removing by value or index removal . Sorting a list with sort() organizes elements in increasing order, but requires more computational work compared to simple additions or deletions. Sorting, while simple to implement, can impact performance with large lists as it generally runs in O(n log n) time complexity.

Checking for edge cases like negative numbers in factorial calculations is crucial because the factorial function is only defined for non-negative integers. The provided Python program addresses this by incorporating a conditional statement that checks for negative input values, and outputs an error message, 'Factorial does not exist for negative numbers', if a negative number is entered . This prevents the program from entering an infinite recursive loop, thereby avoiding runtime errors and ensuring compliance with the mathematical definition of factorial.

You might also like