0% found this document useful (0 votes)
18 views

Illustrative Problems

Uploaded by

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

Illustrative Problems

Uploaded by

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

UNIT 1

1.Find minimum in a list


Algorithm: Find minimum in a list
Step 1: Start
Step 8: Initialize i=1
Step 2: Read n
Step 9: If i<n, then go to step 10 else goto step 13
Step 3: Initialize i=0
Step 10: If a[i]<min, then goto step 11,12 else goto
Step 4: If i<n, then goto step 5,6 else goto
step 12
step 7
Step 11: min=a[i]
Step 5: Read a[i]
Step 12: i=i+1 goto 9
Step 6: i=i+1 goto step 4

Step 7: Compute min=a[0] Step 13: Print min

Step 14: Stop


Pseudo code: Find minimum in a list

BEGIN READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
COMPUTE min=a[0]
FOR i=1 to n, then
IF a[i]<min, then
CALCULATE min=a[i]
INCREMENT i
ELSE
INCREMENT i
END IF
END FOR
PRINT min
END
Flowchart: Find minimum in a list
2.Insert a card in a list of sorted cards
Algorithm: Insert a card in a list of sorted cards
Step 1: Start
Step 2: Read n Step 10: a[i+1]=a[i]
Step 3: Initialize i=0 Step 11: i=i-1 goto step 9
Step 4: If i<n, then goto step 5, Step 12: Compute a[i+1]=item
6 else goto step 7 Step 13: Compute n=n+1,i=0
Step 5: Read a[i] Step 14: If i<n, then goto step 15,
Step 6: i=i+1 goto step 4 16 else goto step 17
Step 7: Read item Step 15: Print a[i]
Step 8: Calculate i=n-1 Step 16: i=i+1 goto step 14
Step 9: If i>=0 and item<a[i], Step 17: Stop
then go to step 10, 11 else goto
step 12
Pseudocode: Insert a card in a list of sorted cards
BEGIN
READ n
FOR i=0 to n, then
READ a[i]
INCREMENT i
END FOR
READ item
FOR i=n-1 to 0 and item<a[i], then
CALCULATE a[i+1]=a[i]
DECREMENT i
END FOR
COMPUTE a[i+1]=a[i]
COMPUTE n=n+1
FOR i=0 to n, then
PRINT a[i]
INCREMENT i
END FOR
END
Flowchart: Insert a card in a list of sorted cards
3.Guess an Integer in a Range
Algorithm - Guess an Integer in a Range
Pseudocode - Guess an Integer in a Range
Flowchart - Guess an Integer in a Range
4.Towers of Hanoi
Towers of Hanoi

• Tower of Hanoi, is a mathematical puzzle which consists of three towers (pegs) and more

than one rings

• Tower of Hanoi is one of the best example for recursive problem solving.

.
Towers of Hanoi - Conditions

Pre-condition:

These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one
sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.

Post-condition:

All the disk should be moved to the last pole and placed only in ascending order as shown
below.
Towers of Hanoi - Rules

• Only one disk can be moved among the towers at any given time.

• Only the "top" disk can be removed.

• No large disk can sit over a small disk.

• Tower of Hanoi puzzle with n disks can be solved in minimum 2^n−1 steps. This presentation

shows that a puzzle with 3 disks has taken 2^3 - 1 = 7 steps.


Towers of Hanoi - Rules

Input: one disk

• If we have only one disk, then it can easily be moved from source to destination peg.

Input: two disks

• First, we move the smaller (top) disk to aux peg.

• Then, we move the larger (bottom) disk to destination peg.

• And finally, we move the smaller disk from aux to destination peg.
Towers of Hanoi - Steps

The steps to follow are –

Step 1 − Move n-1 disks from source to aux

Step 2 − Move nth disk from source to dest

Step 3 − Move n-1 disks from aux to dest


Towers of Hanoi - Steps
Towers of Hanoi - Algorithm

Step 1: Start

Step 2: Let take the 3 Towers to be source, dest, aux.

Step 3: Read the number of disks n from user.

Step 4: Move n-1 disks from source to aux.

Step 5: Move nth disk from source to dest.

Step 6: Move n-1 disks from aux to dest.

Step 7: Repeat steps 4 to 6, by decrementing n by 1.

Step 8: Stop
Towers of Hanoi - Flowchart
Towers of Hanoi - Pseudocode
BEGIN

DECLARE 3 towers source, dest,aux.

READ n

FOR n>0 THEN

Move n-1 disks from source to aux

Move nth disk from source to dest

Move n-1 disks from aux to dest

n=n-1

END FOR

END
Towers of Hanoi - Recursive Algorithm
Step 1: Start
Step 2: Read n
Step 3: Calculate move=pow(2,n)-1
Step 4: Function call Hanoi(n,Beg,Aux,End)
Step 5: Stop

Sub function Hanoi(n,Beg,Aux,End):


Step 1: If n=0, then Return no disk.
Step 2: else
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End) , Move disk from source to destination
T(n-1,Aux,Beg,End)
Towers of Hanoi - Recursive Pseudocode
BEGIN
READ n
CALCULATE move=pow(2,n)-1
CALL FUNCTION Hanoi(n,Beg,Aux,End) Recursively until n=0
PROCEDURE
IF n=0 then,
No disk to move
Else
T(n-1,Beg,End,Aux)
T(1,Beg,Aux,End), move disk from source to destination
T(n-1,Aux,Beg,En )
END PROCEDURE
END
Towers of Hanoi - Recursive Flowchart
UNIT 2
1. Exchange the values of two Variable
Python Program to Exchange the values of two Variable

Algorithm :

Step 1: Start the Program

Step 2: Read the two numbers

Step 3: Swap two variables using Temporary Variables

Step 4: Print the results

Step 5: Stop the program


Python Program to Exchange the values of two Variable
without Function
a=input("Enter the value of a:")
b=input("Enter the value of b:")
print("The values a and b before swapping:",a,b)
temp = a
a=b
b= temp
print("The values a and b after swapping:",a,b)

Output:
Enter the value of a: 10
Enter the value of b: 15
The values before swapping 10, 15
The values after swapping 15, 10
Python Program to Exchange the values of two Variable
within Function
def swap(a,b):
temp=a
a=b
b=temp
print("The values a and b after swapping:", a, b)
n1=int(input("Enter the value of n1:"))
n2=int(input("Enter the value of n2:"))
print ("The values of n1 and n2 before swapping:", n1, n2)
swap(n1,n2)
Output:
Enter the value of n1: 10
Enter the value of n2: 15
The values of n1 and n2 before swapping: 10, 15

The values a and b after swapping: 15, 10


Without Temporary Variable
Python Program to Exchange the values of two Variable
without Temporary Variable Using Tuples
a=input("Enter the value of a:")
b=input("Enter the value of b:")
print("The values a and b before swapping:",a,b)
(a,b)=(b,a)
print("The values a and b after swapping:",a,b)

Output:
Enter the value of a: 10
Enter the value of b: 15
The values before swapping: 10, 15
The values after swapping: 15, 10
2. Circulate the Values of n Variable
Circulate the Values of n Variable

Algorithm :

Step 1: Start the Program

Step 2: Read the Number of Terms

Step 3: Read the values and store it in list

Step 5: Using range function and Pop Function to circulate the Variables

Step 6: Print the Result

Step 7: Stop the Program


Circulate the Values of n Variable

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


list1 = []
for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,n,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
Circulate the Values of n Variable
Output:
3. Calculate Distance Between Two
Points
Python Program to Calculate Distance Between Two Points
( Co-ordinates)

Algorithm :

Step 1: Start the Program

Step 2: Read the X, Y Coordinate values for point 1 and Point 2

Step 3: Calculate the Distance Using the formula sqrt (((x2-x1)**2) + ((y2-y1)**2))

Step 5: Print the Distance

Step 6: Stop the Program


Python Program to Calculate Distance Between Two Points
( Co-ordinates)

# Reading co-ordinates
x1 = float(input('Enter x1: '))
y1 = float(input('Enter y1: '))
x2 = float(input('Enter x2: '))
y2 = float(input('Enter y2: '))
# Calculating distance
d = math.sqrt(( (x2-x1)**2) + ((y2-y1)**2 ))
Python Program to Calculate Distance Between Two Points
( Co-ordinates)

import math
def distance(x1,y1,x2,y2):
dx=x2-x1
dy=y2-y1
f=dx**2 + dy**2
result=math.sqrt(f)
return result
a=int(input("Enter the value of x- coordinate of point 1:"))
b=int(input("Enter the value of y- coordinate of point 1:"))
c=int(input("Enter the value of x- coordinate of point 2:"))
d=int(input("Enter the value of y- coordinate of point 2:"))
r=distance(a,b,c,d)
print("The distance between (",a,",",b,“ )and (",c,",",d,") is",r)
Python Program to Calculate Distance Between Two Points
( Co-ordinates)

Output:
UNIT 3
Quadratic Equation
Quadratic Equation
Quadratic Equation
Quadratic Equation

import math
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))

# calculate the D
d = (b**2) - (4*a*c)

# find two solutions


sol1 = (-b-math.sqrt(d))/(2*a)
sol2 = (-b+math.sqrt(d))/(2*a)
print('The solution are {0} and {1}'. (sol1,sol2))
Quadratic Equation
Sum an array of Integers
Sum an array of Integers – ( Using Iteration)

Algorithm:
Step 1: Start the Program
Step 2: Initialize the Array with values
Step 3: Initialize Sum =0
Step 4: for i in range(len(arr))
Step 4.1: Caluculate Sum= sum +arr[i]
Step 5: Print Sum
Step 6: Stop the program
Sum an array of Integers – ( Using Iteration)
Sum an array of Integers – ( Using Iteration)

arr = [10, 89, 9, 56, 4, 80, 8]

Sum = 0

for i in range(len(arr)):

Sum = Sum + arr[i]

print (Sum)
Sum an array of Integers – ( Using in-built Function)

Using in-built function sum(arr), we can get the sum of the elements
of the array passed to it.
Sum an array of Integers – Runtime Input
Exponentiation
Exponentiation– ( Using Exponential Operator)

Algorithm:
Step1: Start the program
Step 2: Get the base Number
Step 3: Get the Exponential Value / Power Value
Step 4: Calculate base ** Power
Step 5: Print the result
Step 6: Stop the Program
Exponentiation– ( Using Exponential Operator)

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

exp=int(input("Enter exponential value: "))

result=num**exp

print("Result is:",result)
Exponentiation– ( Using Built in Method)

import math
num=int(input("Enter number: "))
exp=int(input("Enter exponential value: "))
result=math.pow(num,exp)
print("Result is:",result)
Greatest Common Divisor ( GCD)
Greatest Common Divisor ( GCD)

Algorithm:
 Initialize GCD = 1

 Run a loop in the iteration of (i) between [1, min(num1, num2)]

 Note down the highest number that divides both num1 & num2

 If i satisfies (num1 % i == 0 and num2 % i == 0) then new value of GCD


is i

 Print value of GCD


Greatest Common Divisor ( GCD)
Greatest Common Divisor ( GCD) Using Built In Functions

• The math.gcd() method returns the greatest common divisor of the two integers int1
and int2.
• GCD is the largest common divisor that divides the numbers without a remainder.
• GCD is also known as the highest common factor (HCF).

Syntax:
math.gcd(int1, int2)

Parameter Values
Greatest Common Divisor ( GCD) Using Built In Functions

# math module contains the gcd function


import math
# now, let's calculate the gcd of 2 numbers.
x = 10
y=4
hcf = math.gcd(x,y)
print("The GCD of {x} and {y} is {hcf}.")
Linear Search
Linear Search

 Linear search is a method of finding elements within a list.

 It is also called a sequential search.

 It is the simplest searching algorithm because it searches the desired element in a

sequential manner.

 It compares each and every element with the value that we are searching for. If both

are matched, the element is found, and the algorithm returns the key's index position.
Linear Search - Concept
Linear Search – Python Script
def linear_Search(list1, n, key):
# Searching list1 sequentially
for i in range(0, n):
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
key = 7
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Binary Search
Binary Search

• Binary Search is a searching algorithm used in a sorted array by repeatedly dividing

the search interval in half.

• Searching is the process of finding some particular element in the list.

• If the element is present in the list, then the process is called successful, and the

process returns the location of that element.

• Otherwise, the search is called unsuccessful.


Binary Search

• Binary search is the search technique that works efficiently on sorted lists.

• Binary search follows the divide and conquer approach in which the list is divided

into two halves, and the item is compared with the middle element of the list.

• If the match is found then, the location of the middle element is returned.

• Otherwise, we search into either of the halves depending upon the result produced

through the match.


Binary Search – Basic Steps

1. Sort the array in ascending order.


2. Set the low index to the first element of the array and the high index to the last
element.
3. Set the middle index to the average of the low and high indices.
4. If the element at the middle index is the target element, return the middle index.
5. If the target element is less than the element at the middle index, set the high index to
the middle index – 1.
6. If the target element is greater than the element at the middle index, set the low index
to the middle index + 1.
7. Repeat steps 3-6 until the element is found or it is clear that the element is not
present in the array.
Binary Search – Recursive Method

Recursive method of binary search follows the divide and conquer


approach.
Binary Search – Recursive Method
Binary Search – Recursive Method
Binary Search – Recursive Method
Binary Search – Python Code
# Binary Search in python
def binarySearch(array, x, low, high):
if high >= low:
mid = low + (high - low)//2
# If found at mid, then return it
if array[mid] == x:
return mid
# Search the left half
elif array[mid] > x:
return binarySearch(array, x, low, mid-1)
# Search the right half
else:
return binarySearch(array, x, mid + 1, high)
Binary Search – Python Code
else:
return -1

array = [3, 4, 5, 6, 7, 8, 9]
x=4
result = binarySearch(array, x, 0, len(array)-1)
if result != -1:
print("Element is present at index " + str(result))
else:
print("Not found")
UNIT 4
Simple Sorting
Simple Sorting

#List of Integers
Numbers=[1,3,4,2]
#sorting list of integers
Numbers.sort()
Print(numbers)
#list of decimal numbers
Decimalnumber=[2.01.2.00,3.67,3.28,1.68]
Decimalnumber.sort()
Print(decimalnumbers)
Output:
#list of strings
1, 2, 3, 4
words=[‘welcome’, ‘all] 1.68, 2.0, 2.01, 3.28, 3.67
Words.sort() all , welcome
Print(words)
SELECTION SORT

 The selection sort select the smallest element in the list.


When the element is found, it is swapped with the first
element in the list.

 Then the second smallest element in the list is then


searched. When the element is found, it is found, it is
swapped with the second element in the list.

 This process of selection and exchange


continues, until all the elements in the list have
been sorted in ascending order.
SELECTION SORT
SELECTION SORT
def selectionsort( a ):
for i in range( len( a ) ):
least = i
for k in range( i + 1 , len( a ) ):
if a[k] < a[least]:
least = k
temp = a[least]
a[least] = a[i]
a[i] = temp
a = [50,30,10,20,40,70,60]
print("Original List is...")
print(a)
selectionsort(a) #Call to the function
print("The sorted List is...")
print(a)
INSERTION SORT

 It start with the second element and put it in its correct place, so
that the first and second elements of the list are in order. This
process continues until all the elements have been sorted

 Insertion sort performs of n-1 passes.

 For pass p=1 through n-1, insertion sort ensures that the elements
in position 0 through p are in sorted order.

 In pass p, we move the element in position p to the left until its


correct place is found.
INSERTION SORT
INSERTION SORT

def insertionsort( a):


for i in range( 1, len( a ) ):
tmp = a[i]
k=i
while k > 0 and tmp < a[k - 1]:
a[k] = a[k - 1]
k -= 1
a[k] = tmp
a = [50,30,10,20,40,70,60]
print("Original List is...")
print(a)
insertionsort(a)
print("The sorted List is...")
print(a)
MERGE SORT

• Merge sort uses divide and conquer method. The problem is divided into smaller
problem and solved recursively. Finally it merges two sorted list.

• Basic algorithm:
i. Divide the given array of elements into two half.
ii. Recursively sort the first half and second half of array elements.
iii. Take two input arrays A and B, an output array C
iv. The first element of A array and B array are compared, then the smaller
element is sorted in the output array C, the corresponding pointer is incremented.
v. This step is repeated until all the elements are compared.
MERGE SORT
MERGE SORT

def mergesort(a):
if len(a) < 2:
return a
middle = int(len(a)/2)
left = mergesort(a[:middle])
right = mergesort(a[middle:])
return merge(left, right)
a=[30,50,10,40,20]
print("Before sorting ...")
print(a)
print("After sorting ...")
print(mergesort(a))
QUICK SORT

• Quick sort uses divide and conquer method

• Basic algorithm:
i. If the number of elements in S is 0 or 1, then return
ii. Pick any element v in S. this is called the pivot
iii. Partition S-{v} (the remaining elements in S) into two
disjoint groups: return {quicksort(S1) followed by v
followed by v followed by quicksort(s2)}
QUICK SORT
QUICK SORT

def quickSort(array, low, high):


if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
data = [1, 7, 4, 1, 10, 9, -2]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
BUBBLE SORT

• Bubble sort is a sorting algorithm that compares two adjacent


elements and swaps them until they are in the intended order.

• Just like the movement of air bubbles in the water that rise up
to the surface, each element of the array move to the end in
each iteration. Therefore, it is called a bubble sort.
BUBBLE SORT
BUBBLE SORT

def bubbleSort(array):
for i in range(len(array)):
for j in range(0, len(array) - i - 1):
if array[j] > array[j + 1]:
temp = array[j]
array[j] = array[j+1]
array[j+1] = temp
data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Histograms
HISTOGRAM
Definition of Histogram : Histogram is visual representation of the distribution of quantitative variable. It is
appeared as vertical bar graph. It represents the distribution of variable being studied.

Parts of Histogram:
Title : The title gives a brief description of what the information is represented by the histogram.

Horizontal or X-Axis : The horizontal or X-axis shows you the range or the values of gaps in between variables. They
are commonly called class intervals which represent or summarize large data sets.
Vertical or Y-Axis : The vertical or Y-axis represents the range values of frequencies or the number of times that the
class intervals occurred.
Bars : The bars represent the object, item, event, or person from where the variables arise. Their height denotes their
respective frequencies, while the bar placement along the X-axis indicates their respective interval values. The width,
however, is the same for all bars.
Bin : Histograms use bins to display data-where a bin represents a given range of values. It is very simple to plot the
Histogram in Python, but for that we need to install few libraries – namely numpy, scipy and mathplotlib.
HISTOGRAM
Histogram

import matplotlib.pyplot as plt


from numpy.random import normal
gaussian_numbers = normal(size=1000)
#plt.hist(gaussian_numbers)
plt.hist(gaussian_numbers)
plt.title("Gaussian Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Histogram
Histogram
# Python program to create a histogram using the matplotlib function
# Importing the required libraries
from matplotlib import pyplot as plt
import numpy as np
# Creating a sample dataset
a = np.array([22, 87, 5, 43, 56,
73, 55, 54, 11,
20, 51, 5, 79, 31,
27])
# Creating histogram using hist( ) function
fig, ax = plt.subplots(figsize =(10, 7))
ax.hist(a, bins = [0, 20, 40, 60, 80,100])
# Showing the plot
plt.show()
Histogram
Student Mark Statement
Student Mark Statement

Problem Description
The program takes in the marks of 5 subjects and displays the grade.
Problem Solution
1. Take in the marks of 5 subjects from the user and store it in different
variables.
2. Find the average of the marks.
3. Use an else condition to decide the grade based on the average of the
marks.
4. . Exit.
Student Mark Statement
#Enter five subject Marks
sub1=int(input("Enter marks of the first subject: "))
sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))
sub4=int(input("Enter marks of the fourth subject: "))
sub5=int(input("Enter marks of the fifth subject: "))
#Calculate Average
avg=(sub1+sub2+sub3+sub4+sub4)/5
print(“First Subject Mark”,sub1)
print(“Second Subject Mark”,sub2)
print(“Third Subject Mark”,sub3)
print(“Fourth Subject Mark”,sub4)
print(“Fifth Subject Mark”,sub5)
Print(“Average”,avg)
Student Mark Statement
#Find Grade and print
if(avg>=90):
print("Grade: A")
elif(avg>=80&avg<90):
print("Grade: B")
elif(avg>=70&avg<80):
print("Grade: C")
elif(avg>=60&avg<70):
print("Grade: D")
else:
print("Grade: F")
Student Mark Statement
Output:
Enter the First Subject Mark: 85
Enter the Second Subject Mark: 95
Enter the Third Subject Mark: 99
Enter the Fourth Subject Mark: 93
Enter the Fifth Subject Mark : 98

First Subject Mark: 85


Second Subject Mark: 95
Third Subject Mark: 99
Fourth Subject Mark: 93
Fifth Subject Mark: 98

Average: 93
Grade : A
Retail Bill Preparation
Retail Bill Preparation
#simple retail bill preparation
a=0
b=0
sum=0
While true:
item=input(‘Item’)
unit=input(‘Enter the unit’)
a=int(unit)
price=input(‘Enter the price’)
b=int(price)
sum+=a*b
next_item=input(‘Is There another item?’)
if(next_item!=‘yes’):
print(‘Please Choose between yes or no’)
if(next_item==‘no’):
break
Print(‘Total Amount for Items Purchased:’, sum)
Retail Bill Preparation
Output
Item : Milk
Enter the Unit: 10
Enter the Price : 50
Is there another Item? Yes

Item: Bread
Enter the Unit: 5
Enter the Price : 30
Is there another Item? No

Total Amount for Items Purchased: 650


UNIT 5
Word Count in file
Word Count in file

Program:
file = open("C:\data.txt", "r")
data = file.read()
words = data.split()

print('Number of words in text file :', len(words))

Input : data.txt
Welcome to www.pythonexamples.org. Here, you will Output
find python programs for all general use cases.
Number of words in text file : 21
This is another line with some words.
Copy File
Copy File (Method 1)

Program:
Output
with open("test.txt") as f:

with open("out.txt", "w") as f1:

for line in f:

f1.write(line)
Copy File (Method 2)
Voters Age Validation
Voters Age Validation ( Method 1)
#this program check voting eligibility
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18: Output 1:
print("Eligible to vote") Enter your age 24
else: Eligible to vote
print("Not eligible to vote")
except ValueError: Output 2:
print("age must be a valid number") Enter your age 6T
except IOError: Enter correct value
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
Voters Age Validation ( Method 2)
import datetime
Year_of_birth=int(input(“In which year you took birth:”))
Current_year=datetime.datetime.now().year
Current _age=current year-year of birth
Print(“your current age is:”,Current_age)
if (Current age>=18):
Output 1:
print(“You are eligible to vote”)
else: In which year you took birth:2000
your current age is:22
print(“you are not eligible to vote”) You are eligible to vote
Mark Range Validation ( 0 – 100 )
Mark Range Validation ( 0 – 100 )
Name=input(“Enter the student name:”)
Regno=input(“Enter the student Register Number:”)
try:
mark1=int(input(“Enter the Mark1:”))
mark2=int(input(“Enter the Mark2:”))
if(0<=mark1<=100)and(0<=mark2<=100):
print(“Marks are in the range”)
else:
raise ValueError(“Marks are not in the range”)
Except ValueError as err:
Print(err)
finally:
#code to be excecuted when there is no exception
print(“Thankyou,you have successfully checked”)
Mark Range Validation ( 0 – 100 )
Output 1:
Enter the student name: ABC

Enter the student register number:1002

Enter the mark1:100

Enter the mark2:90

Marks are in the range

Thank you, you have successfully checked


Mark Range Validation ( 0 – 100 )
Output 2:
Enter the student name: XYZ

Enter the student Register number:1001

Enter the mark1:101

Enter the mark2:90

Marks are not in the range

Thank you, you have successfully checked

You might also like