Find the largest and smallest number in python using for loop
Write a python program to find the largest and smallest number in python using for loop
- Assign first element of an array to largest(lt) and smallest (st) value variable.
- Traverse the array by using for loop
- If element of array a[i] is smaller than first element of variable st then assign array element to st.
- else if, array element a[i] is larger than first element of variable lt then assign array element to lt.
a = [5, 3, 2, 8]
st = a[0]
lt = a[0]
l = len(a)
for i in range(l):
if a[i] < st:
st = a[i]
elif a[i] > lt:
lt = a [i]
print("Small: {}, Large: {} ".format(st,lt))
Output:
Small: 2, Large: 8
More Python Programming Questions & Answer
(Visited 4,899 times, 17 visits today)