Exercise 3.3 on Unit 3

Could anyone explain to me the below exercise with for loop?
ĪšĪ±Ļ„Ī±Ī³ĻĪ±Ļ†Ī®

The solution

from robot_control_class import RobotControl

robotcontrol = RobotControl()

l = robotcontrol.get_laser_full()

maxim = 0

for value in l:
    if value > maxim:
        maxim = value

print ("The higher value in the list is: ", maxim)

Thanks in advance!

Hello @vasileios.tzimas ,

Could you specify a little bit more with your question? What is it that you donā€™t understand? Is it the exercise requirements? Is it the solution code? The entire code? A specific part of the code?

Thanks in advance,

1 Like

Hello again! Yes, of course, I didnā€™t understand how to find the higher value of l. It will have 719 values. Also, what does in do in for loop?

The how is to check each value in the list (array) one by one to determine the largest value, and the for-loop can help you do that.

it means inside
The general structure of a for-loop is

for item in iterable_object:  
  # do something with item

and it simply means ā€œfor every item inside this objectā€ā€¦

That solution could be better written as:

from robot_control_class import RobotControl

robotcontrol = RobotControl()

laser_readings = robotcontrol.get_laser_full()

maxim = laser_readings[0]  # the very first item, let's assume it's the largest for now

for value in laser_readings:
    if value > maxim:
        maxim = value

print ("The higher value in the list is: ", maxim)
  • We set the first item in the laser_readings list as the largest to begin with. We store the value in maxim.
  • We then go over the items in the array one by one and check if they are larger than maxim.
    • If any item is larger than maxim, we store itā€™s value in maxim so that it becomes the largest for the moment and move to the next element and check again. We repeat this check until we have checked all elements.
    • By the time we finish checking all items, the largest value would have been stored in maxim.
  • Eventually, we print the value of maxim.

Thank you very much @bayodesegun !!