Find max and min numbers in Python

thumbnail

In this tutorial, you will learn to create function to find max and min numbers in Python without using max() and min() function.

The source code is explained below:

def max_min(data):
  # 'data' list should no be empty
  # set the first element of 'data' in max_ and min_ variable
  max_ = data[0]
  min_ = data[0]
  
  # Using For loop to find max and min number in 'data'
  for i in data:
    if i>max_:
      max_ = i # we found the new max value
      
    if i<min_:
      min_ = i # we found the new min value
  return max_,min_

d = [54,0,12,48,-24]
max_value, min_value = max_min(d)
print("Find Max and Min value using max_min() function")
print("Max Value: "+str(max_value))
print("Min Value: "+str(min_value))
print("")
print("Find Max and Min value using max() and min() function")
print("Max Value: "+str(max(d)))
print("Min Value: "+str(min(d)))

The output will be:

Find Max and Min value using max_min() function
Max Value: 54
Min Value: -24

Find Max and Min value using max() and min() function
Max Value: 54
Min Value: -24

Browse more to find another python algorithm in this website.

Back To Top