Conditionals are used to make your program follow a certain path if some of the conditions are match, I'll give an example based on our daily life, imagine the necessary actions for you to brush your teeth, take the toothbrush, take the toothpaste, put a little bit of toothpaste on the toothbrush.
Now imagine that we want to make a robot to automatize these actions, how do we program your robot, something like this:
Take the toothbrush
Take the toothpaste tube
Open the toothpaste tube
Put some toothpaste on the toothbrush
Close the toothpaste tube
Everything seems simple, but I'm gonna make it more complicated, what would this robot do if the tooth paste is already open? Will it pick up the tube and try to open it, or will it try opening the tube that is already open, or maybe it will crash.
This can look obvious for us, but in case the tube is already open we know that we don't need to open it, but the robot doesn't think like us.
It's in cases like this that we need the conditionals, to write a better robot program we need to use conditionals so it can executed the proper action based on some environment conditions, let's rewrite our robot actions, but now adding conditionals.
Take the toothpaste tube
If the toothpaste tube end is closed
Open the end
Hold the end
Put some toothpaste on the toothbrush
If holding the end
Close the end
Notice that the action "open the end" is some spaces to the right, I used those spaces to illustrate that this action will be executed just if the line before is is match, in programming these spaces are called indentation, and as we will see on the next lesson, they are very important in Python!
Now let's try making our program better, let's presume you want your robot to beep and stop when you are out of toothpaste, who would we do that?
Again, being out of toothpaste is a condition, let's see how the program would look like:
Take the toothpaste tube
If the toothpaste tube is empty
Beep
Else
If the toothpaste tube end is closed
Open the end
Hold the end
Take the toothbrush
Put some toothpaste on the toothbrush
If holding the end
close the end
Notice that our robot will only work if the toothpaste tube isn't empty, it will test if the toothpaste tube is empty, it if is, it will just stop, if it's not it will execute what is inside the "Else", and if the end is open it will just put some toothpaste on the toothbrush and will not open the end, and if it's not holding the end it will not close the end.
This lesson was just theory, but this theory is very important, so in case you have any doubts, comment!
2 comentários:
hey..fucker...where are the other lessons?
hehe
I'm working on it, sorry, just be patient.
Postar um comentário