RBI Chapter 5
Chapter 5: If, Else & Again
What if you were to set your robot on a mission where it was to find all the hidden treasures in a room? Then, you would not be there to guide it, make it move forward, stop when it is going to hit the wall or make it go to all the corners of the room. Then how would it make its mission possible? That’s where the helpful if-else statements come in. They are also known as conditionals. The way your parents set conditions for you, you can set conditions for your robot. The way they tell you that you can only go out and play if you have finished your homework, you can tell your robot that it can only move forward if it does not see any obstacle in front of it. Of course, the only difference remains that your parents tell you in English, but you talk to your robot in Python!
You would tell your robot something similar to this:
>>> if (you don’t see a wall): forward (speed, sec) else: stop( )
Note, of course, that your robot cannot even understand “you don’t see a wall” and we would have to translate that into Python as well, but we will learn about that later on in the course.
Loop it When you are working on a Math problem and you do not get the correct answer the first time, then what do you do? You go back and try to do it again and again until you get the correct answer. Well, even though your robot should never get that Math problem wrong, it will never do anything again and again unless it is told to do so. When you want your robot to keep doing a command over and over again for any number of times, you should put your commands in a loop. Let’s say you want your robot to move forward and rotate and move forward again and rotate again and you want it to repeat this cycle ten times. Of course, you can sit there and type in the commands one by one again and again and again, but that would not be very time efficient, would it? It would be a waste of your time and a waste of space and energy for the computer. So, let’s put it in a loop!
You could tell your robot something similar to this:
>>> do these ten times: forward(speed, time) turnLeft(speed, time)
Note, of course, that your robot cannot understand “do these ten times” and we would have to translate that into Python as well, but you will learn that soon too.
Activity: Let's Play!
Listen carefully to your instructors to understand and play the Loopif game!
An interactive life-size game was designed for the students to help them learn the concepts of conditionals and loops. The consisted of various educational challenges that the students were required to complete. These included Mathematics, General Knowledge and a Robot Review Section.