[go: up one dir, main page]

0% found this document useful (0 votes)
4 views18 pages

python programming BTech lab manual

The document contains a series of Python exercises covering various programming concepts such as basic syntax, control flow, data structures, file handling, and functions. Each exercise includes code snippets, expected outputs, and explanations for common programming errors and techniques. It serves as a comprehensive guide for beginners to learn and practice Python programming.

Uploaded by

diwakarkhushi69
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)
4 views18 pages

python programming BTech lab manual

The document contains a series of Python exercises covering various programming concepts such as basic syntax, control flow, data structures, file handling, and functions. Each exercise includes code snippets, expected outputs, and explanations for common programming errors and techniques. It serves as a comprehensive guide for beginners to learn and practice Python programming.

Uploaded by

diwakarkhushi69
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/ 18

Exercise 1 – Basics

a) Running instructions in Interactive interpreter and a Python Script


1. To print “welcome to python programming”

2. Using Identifiers, Variables, and Expressions

3. Using Conditional Statements in Python

4. Using if….else in Python


b) Write a program to purposefully raise Indentation Error and Correct it
def max(x,y):
if(x>y):
return x
else:
return y
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Finding the Maximum out of a:", a ,"and b:", b)
c=max(a,b)
print(c,"is maximum")

Output:
ERROR!
File "<string>", line 3
return x
^
IndentationError: expected an indented block after 'if' statement on line 2

To correct the error we should use indention in line 3.


def max(x,y):
if(x>y):
return x
else:
return y
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
print("Finding the Maximum out of a:", a ,"and b:", b)
c=max(a,b)
print(c,"is maximum")

Output:
Enter a number: 2
Enter another number: 23
Finding the Maximum out of a: 2 and b: 23
23 is maximum
Exercise 2 – Operations

a) Write a program to compute distance between two points taking input from the
user (Pythagorean Theorem)

import math
x1=int(input("Enter x1: "))
y1=int(input("Enter y1: "))
x2=int(input("Enter x2: "))
y2=int(input("Enter y2: "))
d1 = (x2 - x1) * (x2 - x1)
d2 = (y2 - y1) * (y2 - y1)
res = math.sqrt(d1+d2)
print ("Distance between two points:",res);

Output:
Enter x1: 2
Enter y1: -4
Enter x2: -2
Enter y2: 4
Distance between two points: 8.94427190999916

b) Write a program that takes 2 numbers as command line arguments and prints its
sum.

x = int(input("Enter x: "))
y = int(input("Enter y: "))
print(x+y)

Output:
Enter x: 2
Enter y: 4
6
Exercise - 3 Control Flow

a) Write a Program for checking whether the given number is a even number or not.
num = int(input("Enter a number: "))
if (num % 2) == 0:
print(num,"is even")
else:
print(num,"is odd")

Output:
Enter a number: 22
22 is even

b) Using a for loop, write a program that prints out the decimal equivalents of 1/2, 1/3,
1/4, . . . ,1/10
a=1
for b in range(2,11):
print(f'{a}/{b}:',a/b)

Output:
1/2: 0.5
1/3: 0.3333333333333333
1/4: 0.25
1/5: 0.2
1/6: 0.16666666666666666
1/7: 0.14285714285714285
1/8: 0.125
1/9: 0.1111111111111111
1/10: 0.1

c) Write a program using a for loop that loops over a sequence.


s = "I am a Python developer"
for i in s:
print(i,end='')

Output:
I am a Python developer
d) Write a program using a while loop that asks the user for a number, and prints a
countdown from that number to zero.
n = int(input("Enter a no. "))
while n>=0:
print(n,end=' ')
n=n-1

Output:
Enter a no.
10
10 9 8 7 6 5 4 3 2 1 0
Exercise 4 - Control Flow – Continued

a) Find the sum of all the primes below two million. Adding the previous two terms, each
new term in the Fibonacci sequence is generated. By starting with 1 and 2, the first 10
terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
n = 2000000
num1 = 0
num2 = 1
next_number = num2
Total = 0

def prime(num):
if num > 1:
for i in range(2, int(num/2)+1):
if (num % i) == 0:
return 0
else:
return num
return 0

while next_number <= n:


Total+=prime(next_number)

num1, num2 = num2, next_number


next_number = num1 + num2

print(Total)

Output:
544828

b) By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even valued terms.
nterms = 4000000
n1, n2 = 0, 1
nth = n2
total=0
while nth <= nterms:
if nth%2==0:
total+=nth
nth = n1 + n2
n1 = n2
n2 = nth

print(total)

Output:
4613732

c) Linear search and Binary search


1. Linear search
def linearSearch(array, n, x):

for i in range(0, n):


if (array[i] == x):
return i
return -1

array = [24, 41, 31, 11, 9]


x = 11
n = len(array)
result = linearSearch(array, n, x)
if(result == -1):
print("Element not found")
else:
print("Element is Present at Index: ", result)

Output:
Element found at index: 3

2. Binary search
def binarySearch(array, x, low, high):
while low <= high:
mid = low + (high - low)//2
if array[mid] == x:
return mid
elif array[mid] < x:
low = mid + 1
else:
high = mid - 1
return -1

array = [2, 4, 5, 17, 14, 7, 11, 22]


x = 22

result = binarySearch(array, x, 0, len(array)-1)


if result != -1:
print("Element is found at index",result)
else:
print("Not found")

Output:
Element is found at index 7

d) Selection sort, Insertion sort


1. Selection sort
def selectionSort(array, size):

for step in range(size):


min_idx = step

for i in range(step + 1, size):


if array[i] < array[min_idx]:
min_idx = i
(array[step], array[min_idx]) = (array[min_idx], array[step])

data = [-2, 45, 0, 11, -9]


size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

Output:
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]

2. Insertion sort
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1

while j >= 0 and key < array[j]:


array[j + 1] = array[j]
j=j-1
array[j + 1] = key

data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)

Output:
Sorted Array in Ascending Order:
[1, 3, 4, 5, 9]
Exercise - 5 – DS

a) Write a program to count the numbers of characters in the string and store them in a
dictionary data structure
str=input("Enter a String:")
dict = {}
for n in str:
keys = dict.keys()
if n in keys:
dict[n] += 1
else:
dict[n] = 1
print (dict)

Output:
Enter a String:I am a Programmer
{'I': 1, ' ': 3, 'a': 3, 'm': 3, 'P': 1, 'r': 3, 'o': 1, 'g': 1, 'e': 1}

b) Write a program to use split and join methods in the string and trace a birthday with
a dictionary data structure.

people = {}

for i in range(2):
s1 = input("Enter the name: ")
s2 = input("Enter the DOB: ")
s2 = s2.split()
people[s1]=s2

for i,j in people.items():


j= ','.join(j)
print(i,"has DOB",j)

Output:
Enter the name: Steven Smith
Enter the DOB: 2 June 1989
Enter the name: Robert Downey Jr.
Enter the DOB: April 4 1965
Steven Smith has DOB 2,June,1989
Robert Downey Jr. has DOB April,4,1965
Exercise – 6 DS – Continued

a) Write a program combine_lists that combines these lists into a dictionary.

list1=[1,2,'cse',4,5]
list2=['khit',7,'cse',9]

combined_list = list1 + list2


dict1={}
for i in range(len(combined_list)):
dict1[i]=combined_list[i]

print("The dictionary is------>",dict1)

Output:
The dictionary is------> {0: 1, 1: 2, 2: 'cse', 3: 4, 4: 5, 5: 'khit', 6: 7, 7: 'cse', 8: 9}

b) Write a program to count frequency of characters in a given file. Can you use
character frequency to tell whether the given file is a Python program file, C program
file or a text file?

For example a.txt file contains “hi”

import os
count =0
file=open("D:/a.txt")

for line in file:


for l in range(0,len(line)):
count+=1;

print("count:",count)

filename,file_extension = os.path.splitext("D:/a.txt");
print("file_extension==",file_extension);

if(file_extension=='.py'):
print("its python program file");
elif(file_extension==".txt"):
print("its a txt file");
elif(file_==extension==".c"):
print("its a c program file");

Output:
count: 2
file_extension== .txt
its a txt file
Exercise - 7 Files

a) Write a program to print each line of a file in reverse order.


For example a.txt file contains Gita

input_file=open('D:/a.txt','r')

for line in input_file:


l=len(line)
s=' '
while(l>=1):
s=s+line[l-1]
l=l-1
print(s)
input_file.close()

Output:
atiG

b) Write a program to compute the number of characters, words and lines in a file.

k=open('D:/a.txt','r')
char,wc,lc=0,0,0

for line in k:
for i in range(0,len(line)):
char +=1
if(line[i]==' '):
wc+=1
if(line[i]=='\n'):
wc = wc+1
lc=lc+1

print("The no. of chars is",char)


print("The no. of words is",wc)
print("The no. of lines is",lc)
Output:
The no. of chars is 21
The no. of words is 2
The no. of lines is 2
Exercise - 8 Functions

a) Write a function ball_collide that takes two balls as parameters and computes if they
are colliding. Your function should return a Boolean representing whether or not the
balls are colliding. Hint: Represent a ball on a plane as a tuple of (x, y, r), r being the
radius If (distance between two balls centers) <= (sum of their radii), then (they are
colliding)

import math
def ball_collide(x1,y1,r1,x2,y2,r2):
dist=math.sqrt((x2-x1)**2+(y2-y1)**2);
print("Distance b/w two balls:",dist)
center=dist/2;
print("Collision point",center);
r=r1+r2;
print("Sum of radious",r)
if(center<=r):
print("They are Colliding")
return True;
else:
print("Not Colliding")
return False;

c=ball_collide(4,4,3,2,2,3)
print(c)
c=ball_collide(100,200,20,200,100,10)
print(c)

Output:
Distance b/w two balls: 2.8284271247461903
Collision point 1.4142135623730951
Sum of radious 6
They are Colliding
True
Distance b/w two balls: 141.4213562373095
Collision point 70.71067811865476
Sum of radious 30
Not Colliding
False

b) Find the mean, median, and mode for the given set of numbers in a list.

from statistics import mean,median,mode


l = [15, 18, 2, 36, 12, 78, 5, 6, 9,18]
print("Mean",mean(l))
print("Median",median(l))
print("Mode",mode(l))

Output:
Mean 19.9
Median 13.5
Mode 18
Exercise - 9 Functions – Continued

a) Write a function nearly_equal to test whether two strings are nearly equal. Two
strings a and bare nearly equal when a single mutation on b can generate a.

from difflib import SequenceMatcher


def Nearly_Equal(a,b):
return SequenceMatcher(None,a,b).ratio();
a="khit"
b="khitc"
c=Nearly_Equal(a,b)

if(c*100>80):
print("Both Strings are similar")
print("a is mutation on b")
else:
print("Both Strings are Different")

Output:
Both Strings are similar
a is mutation on b

b) Write a function dups to find all duplicates in the list.

def dups():
for i in a:
d[i]=0

for i in a:
d[i] = d[i]+1

for i in d:
if d[i]>1:
ans.add(i)

a = [2,3,6,4,78,4,65,2,4,5]
ans = set()
d={}
dups()
print(ans)

Output:
{2, 4}
c) Write a function unique to find all the unique elements of a list.

def unique():
for i in a:
d[i]=0

for i in a:
d[i] = d[i]+1

for i in d:
if d[i]==1:
ans.add(i)

a = [2,3,6,4,78,4,65,2,4,5]
ans = set()
d={}
unique()
print(ans)

Output:
{65, 3, 5, 6, 78}
Exercise - 10 - Functions –Problem-Solving

a) Write a function cumulative_product to compute the cumulative product of a list of


numbers.

def product(list):
p =1
for i in list:
p *= i
print(p)

arr= [1,2,3,4,5,6,7,8,9,10]
product(arr)

Output:
1
2
6
24
120
720
5040
40320
362880
3628800

b) Write a function reverse to reverse a list. Without using the reverse function.

def reverse(list):
size = len(arr)
size = -size
i=-1
while i>=size:
rev.append(arr[i])
i= i-1
size = -size
for i in range(size):
arr[i] = rev[i]

arr= [1,2,3,4,5,9,10]
rev = []
reverse(arr)
print(arr)
Output:
[10, 9, 5, 4, 3, 2, 1]

c) Write a function to compute gcd, lcm of two numbers. Each function shouldn’t
exceed one line.

import math
n1 = int(input("Enter n1 value:"))
n2 = int(input("Enter n2 value:"))

print("GCD value is:",math.gcd(n1, n2))

print("LCM value is:",int(n1 * n2 / math.gcd(n1, n2)))

Output:
Enter n1 value:12
Enter n2 value:18
GCD value is: 6
LCM value is: 36

You might also like