One of the most basic things in programming is the if statement. This is a block of code that runs "if" something is true. This could be a mathematical statement like "if x is bigger than 5" or it would be something like "if the list contains apples." If the condition is false, the code simply doesnβt run. We will learn how to use if statements in this section.
So far, we have been using the equals sign (=) to set a variable to a value. But, to check if two things are equal in python, we use a double equals sign (==). This is common in many programming languages.
Below, we set the value of x to be 5. Then we check if x is equal to 5. If it is, we add 1 to x. Finally, we print the value of x. Python uses indentation to show what code is inside the if statement. The line that is indented after the if statement is the only line that will run if the condition is true.
This time, the statement we were checking was false, so the code indented after the if statement did not run. The values of x is still 5. We did not add 1 to it.
It is also possible to check if two things are not equal. This is done with the "not equal" operator (!=). Letβs check if x is not equal to 7, and then add 1 if that is the case.
When you read inequality, you probably thought about "greater than" or "less than or equal." Those are also possible in if statements. The symbols you would use are:
Since x is not greater than 5, the if condition is false, and we do not add 10 to x. But, since if was false, the else statement runs, and x is multiplied by 4. The value of x is now 8.
Set a variable k equal to 95. Check if k is greater than or equal to 100. If it is, subtract 20 from k. Otherwise, subtract 5 from k. Finally, print k. What is the value of k?
The value of k is 90 because 95 is not greater than or equal to 100, so the if statement does not run. Instead, the else statement is applied. So, 5 is subtracted from k.