While Exercising for Proof

0

I can not do this exercise, neither with while nor with for. If you can give me the way you do with While and For, I'll be grateful.

  
  • Given a list of numbers, say the largest number on the list. Use the len () function to find out the list size and the while repeat structure to cycle through the list.
  •   

    Remembering that the program should be done exactly as it is requested in the exercise.

    Code that I managed to do, however super wrong:

    lista = [0, 10, 20, 50, 80]
    maior = lista[0]
    
    while maior in lista < maior:
        print(maior)
    
        
    asked by anonymous 24.05.2017 / 19:19

    1 answer

    1

    Well, I will not go into the merits of how hard you should have tried or not to do this.

    Basically, you need to go through all the elements of the list and check which one is the largest. This can be done in several ways.

    What I did in my code was to have the variable i receive at each loop a valid index (from lista ), that is, it starts at 0 and goes to len(lista) - 1 . And then check if the element in this index is greater than the highest one saved so far (in the variable maior )

    lista = [0, 10, 20, 50, 80]
    
    maior = lista[0]
    i = 0
    while i < len(lista):
        if lista[i] > maior:
            maior = lista[i]
        i += 1
    
    print('O maior é {}'.format(maior))
    

    See working on repl.it.

    You can do this without using any loop , with the function max()

    maior = max(lista)
    
        
    24.05.2017 / 19:28