Header Ads Widget

Ticker

6/recent/ticker-posts

Programming With Python Syllabus and Lab Manual and Practicals

 

Syllabus:-


Lab Manual:-

Practical 1:- Introduction to various IDE for programming in python.




Practical 2:- Data Types, Operators and conditional statements

 (a) Write a program to print “Hello World”.
# This program prints Hello, world!

print('Hello, world!')
Output
Hello, world!
(b) Write a program to find the maximum number out of 3 numbers.
# Python program to find the largest
# number among the three numbers
 
def maximum(a, b, c):
 
    if (a >= b) and (a >= c):
        largest = a
 
    elif (b >= a) and (b >= c):
        largest = b
    else:
        largest = c
         
    return largest
 
 
# Driven code
a = 10
b = 14
c = 12
print(maximum(a, b, c))

Output:-

14

(c) Write a program to swap the values of two variables without using temporary variable

X=15
Y=10
print("Before Swapping",X,Y)
X,Y=Y,X
print("After Swapping",X,Y)

Output:-

Before Swapping 15 10
After Swapping 10 15

(d) Write a program to implement calculator.

# Program make a simple calculator

# This function adds two numbers
def add(x, y):
    return x + y

# This function subtracts two numbers
def subtract(x, y):
    return x - y

# This function multiplies two numbers
def multiply(x, y):
    return x * y

# This function divides two numbers
def divide(x, y):
    return x / y


print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

while True:
    # take input from the user
    choice = input("Enter choice(1/2/3/4): ")

    # check if choice is one of the four options
    if choice in ('1', '2', '3', '4'):
        num1 = float(input("Enter first number: "))
        num2 = float(input("Enter second number: "))

        if choice == '1':
            print(num1, "+", num2, "=", add(num1, num2))

        elif choice == '2':
            print(num1, "-", num2, "=", subtract(num1, num2))

        elif choice == '3':
            print(num1, "*", num2, "=", multiply(num1, num2))

        elif choice == '4':
            print(num1, "/", num2, "=", divide(num1, num2))
       
        # check if user wants another calculation
        # break the while loop if answer is no
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation == "no":
          break
   
    else:
        print("Invalid Input")

Output

Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
Let's do next calculation? (yes/no): no

(e) Write a Python program to calculate the sum of the digits in an integer.

# Python program to
# compute sum of digits in
# number.

# Function to get sum of digits
def getSum(n):
   
    sum = 0
    for digit in str(n):
    sum += int(digit)  
    return sum

n = 12345
print(getSum(n))


Output:-

15

Practical 3:- Control Structures and Functions:

 a) Write a program for find factorial of a given number using iterative and recursive function.

# Factorial of a number using recursion

def recur_factorial(n):
   if n == 1:
       return n
   else:
       return n*recur_factorial(n-1)

num = 7

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

Output

The factorial of 7 is 5040

b) Write a program which takes a sentence from user and calculates number of digits, letters, uppercase letters, lowercase letter and spaces in sentence.

string=input("Enter string:")
count1=0
count2=0
count3=0
for i in string:
      if(i.islower()):
            count1=count1+1
      elif(i.isupper()):
            count2=count2+1    
      elif(i.isdigit()):
            count3=count3+1
print("The number of lowercase characters is:")
print(count1)
print("The number of uppercase characters is:")
print(count2)
print("The number of digits characters is:")
print(count3)

Output:

Enter string:selfish789
The number of lowercase characters is:
7
The number of uppercase characters is:
0
The number of digits characters is:
3

c) Write a program to find GCD of two numbers

# Python code to demonstrate the working of gcd()
# importing "math" for mathematical operations
import math

print("The gcd of 60 and 48 is : ", end="")
print(math.gcd(60, 48))

Output:-

12

d) Write a program to convert Decimal to hex, octal and binary.

# Python program to convert decimal into other number systems
dec = 344

print("The decimal value of", dec, "is:")
print(bin(dec), "in binary.")
print(oct(dec), "in octal.")
print(hex(dec), "in hexadecimal.")

Output

The decimal value of 344 is:
0b101011000 in binary.
0o530 in octal.
0x158 in hexadecimal.

Practical 4:- Working with Data structure - Part I

    a)Write a program to remove duplicates from list.
student = ["sanskar","priyan","om","soumil","sanskar","soumil"]
print(student)
student1=[]
for i  in student:
  if i not in student1:
    student1.append(i)
print(student1)

    Output:-

['sanskar', 'priyan', 'om', 'soumil', 'sanskar', 'soumil'] ['sanskar', 'priyan', 'om', 'soumil']

    b) Write a program to find frequency of elements of list.
student = ["sanskar","priyan","om","soumil","sanskar","soumil"]
frequency = {}

for i in student:
   if i in frequency:
      frequency[i] += 1
   else:
      frequency[i] = 1
print(frequency)
bb
b
Output:-

{'sanskar': 2, 'priyan': 1, 'om': 1, 'soumil': 2}

c) Write a program to sort given list

student = [12,10,5,8,7,6]
student.sort()
print(student)

Output:-

[5, 6, 7, 8, 10, 12]

d) Write a program for matrix addition and matrix multiplication using list.

a=[[1,2,3],[4,5,6]]
b=[[4,5,6],[1,2,3]]
c=[[0,0,0],[0,0,0]]
for i in range(len(a)):
  for j in range(len(a[0])):
    c[i][j]=a[i][j]+b[i][j]
print("sum of matrix")
for g in c:
  print(g)

for i in range(len(a)):
   for j in range(len(b[0])):
       for k in range(len(b)):
           c[i][j] += a[i][k] * b[k][j]
print("Multiplication of matrix")
for r in c:
   print(r)

Output:-

sum of matrix [5, 7, 9] [5, 7, 9] Multiplication of matrix [11, 16, 21] [26, 37, 48]

G) Write a program to remove an element from tuple

student = ("sanskar","priyan","om","soumil","sanskar","soumil")
print(student)
rem1 = list(student) 
rem1.remove("priyan") 
student = tuple(rem1)
print(student)

Output:

('sanskar', 'priyan', 'om', 'soumil', 'sanskar', 'soumil') ('sanskar', 'om', 'soumil', 'sanskar', 'soumil')


f) Write a program to find minimum and maximum value in list of tuples.

numbers = [(2, 3), (4, 7), (8, 11), (3, 6),(1,5)]
print (str(numbers))

res1 = min(numbers)[0]
res2= max(numbers)[0]
res3 = min(numbers)[1]
res4=max(numbers)[1]

print ("min value of list index 0 " + str(res1)+"min value of list index 1 " +str(res3))
print ("max value of list index 1"+str(res2) + "max value of list index 0 " +str(res4))

Output:-

[(2, 3), (4, 7), (8, 11), (3, 6), (1, 5)] min value of list index 0 1min value of list index 1 5 max value of list index 18max value of list index 0 11

e) Write a program to generate Pascal’s triangle using list.

Update Soon...

Practical 5:- Working with Data structure - Part II:

a) Write a program to map 2 lists into a dictionary.

keys = ['red', 'green', 'blue']
values = ['#FF0000','#008000', '#0000FF']
color_dictionary = dict(zip(keys, values))
print(color_dictionary)

Output:-
{'red': '#FF0000', 'green': '#008000', 'blue': '#0000FF'}

b) Write a program to invert keys and values of dictionary. 

myDict = {1: 1, 2: 4, 3: 9, 4: 16, 5: 1}
print("The input dictionary is:")
print(myDict)
reversedDict = ()
for key in myDict:
    val = myDict[key]
    reversedDict[val] = key
print("The reversed dictionary is:")
print(reversedDict)

Output:-

The input dictionary is: {1: 1, 2: 4, 3: 9, 4: 16, 5: 1} The reversed dictionary is: {1: 5, 4: 2, 9: 3, 16: 4}

c) Write a program to generate dictionary of frequency of alphabets of given string.

str1 = input ("Enter the string: ")
d = dict()
for c in str1:
    if c in d:
        d[c] = d[c] + 1
    else:
        d[c] = 1
print(d)


Output:-

Enter the string: devam {'d': 1, 'e': 1, 'v': 1, 'a': 1, 'm': 1}

 d) Write a Python program to sum all the items in a dictionary.

def returnSum(myDict):
 
    list = []
    for i in myDict:
        list.append(myDict[i])
    final = sum(list)
 
    return final
 
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))


Output:-

Sum : 600

e) Write a script to concatenate given dictionaries

d1={'A':1,'B':2}
d2={'C':3}
d1.update(d2)
print("Concatenated dictionary is:")
print(d1)

Output:-

Concatenated dictionary is: {'A': 1, 'B': 2, 'C': 3}

f) Create a dictionary where keys are name of students and values are another dictionary containing semester, age and cpi of that student.  Print all the names of students.  Print only names of students  Print the name of student having highest CPI 

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

result = {}

for i in range(n):
  print("Enter Details of student No.", i+1)

  name = input("Name: ")
  sem = int(input("Semester:"))
  age = int(input("Age:"))
  cpi = float(input("CPI: "))

  result[name] = {'sem':sem,'age':age,'cpi':cpi}

print(result)

print(result.keys())

for key, value in result.items():
  print(key)


maxCpi=0
maxCpiname=''
for key in result:
  value=result[key]
  tempCpi=int(value["cpi"])
  if(tempCpi>maxCpi):
    maxCpi=tempCpi
    maxCpiname=key

print("Student having highest CPI:",maxCpiname)



Output:-

Enter number of students: 2 Enter Details of student No. 1 Name: raj Semester:3 Age:18 CPI: 9.6 Enter Details of student No. 2 Name: helly Semester:5 Age:19 CPI: 7 {'raj': {'sem': 3, 'age': 18, 'cpi': 9.6}, 'helly': {'sem': 5, 'age': 19, 'cpi': 7.0}} dict_keys(['raj', 'helly']) raj helly Student having highest CPI: raj

Post a Comment

0 Comments