When you execute the program we just wrote you will see the blinking LED. This is happening without the program asking you for your opinion. And being that we have so many beautiful colors for LEDS to choose from, I am sure that you would like to have more options. Well with the help of the “if-statement”, we are able to adapt your decisions into the program. The if-statement has extreme cool superpowers to check if a statement is correct (true), or incorrect (false), and then react accordingly. With this we can check for certain conditions and control the flow of our program’s execution. Let’s take a deeper look into the if statement:
coding = "cool" if coding == "cool": print("coding ist cool!")
In line 1 you can see that we created the variable coding and filled it with the value “cool”.
The new and exciting part takes place in line 2. In this line we use the variable we created before and check if the content is the same as “cool”. To do this we use the Conditional expression
Line 2 is basically saying:
If the content of the Variable coding is equal to the string “cool”, then execute everything which is intended after the colon
:. To make certain coding part of the if-statement you can use the tab key on your keyboard. Please keep in mind that only the intended code is part of the if-statement. In this case only line 3 is executed..
Easy enough right? To get you going we have prepared some examples for your to make sure you understand the principles. Which of following if statements would be executed:
sky = "blue" if sky == "blue": print(“Let’s go to the beach“)
water = "wet" if water == "dry": print(“That’s not so good“)
ball = "round" if ball == "squared": print(“Should a ball be round?”)
We know that you don’t really need the solutions but we have provided it here anyway. Number 1 is true and will be executed. Number 2 of course is false and won’t be executed. Without wet water we couldn’t wash our hands. Number 3 is also false because obviously the balls we know are round ;)