user3376651
user3376651

Reputation: 11

Changing a for loop to a while loop in Python

myList=[1,2,3,5]
def findMax(aList):
     biggest = aList[0]
     for value in aList: 
           if value > biggest:
               biggest = value
     return biggest

This code searches for the largest number in a list.

How would I change this into a while loop, rather than a for loop?

Upvotes: 0

Views: 1086

Answers (4)

radubogdan
radubogdan

Reputation: 2834

myList=[1,2,3,5]
def findMax(aList):
     biggest = aList.pop()
     while(len(aList) > 0):
         element = aList.pop()
         if (element > biggest):
             biggest = element
     return biggest

Upvotes: 1

flakes
flakes

Reputation: 23624

myList=[1,2,3,5]
def findMax(aList):
     biggest = aList[0]
     ii = 1
     while ii < len(aList): 
           if aList[ii] > biggest:
               biggest = aList[ii]
           ii += 1
     return biggest

Upvotes: 0

Oscar Bralo
Oscar Bralo

Reputation: 1907

Try this:

myList=[1,2,3,5]

def findMax(aList):
     i = 0
     biggest = aList[0]
     while (i < len(myList)):
          if myList[i] > biggest:
               biggest = value
          i += 1;
     return biggest

Upvotes: 0

Embattled Swag
Embattled Swag

Reputation: 1469

What you can do is declare a simple counter before you go into the loop and then after you check if the value is greater than biggest, you add one to the counter. Make sure to check if the counter is equal to the size of the array though, so you don't go out of bounds of it. If it is, you can break out of the while loop.

Upvotes: 0

Related Questions