So far our programs have been quite "stiff" - they execute instruction by instruction in the order we've given them and can never deviate from this decided path.
Normal apps or games don't follow a straight path like this. Here, we will see how our code also can start "thinking on its own", and give the user different options to choose.
These two lines are different:
We say that the second line is "indented" to the right. You can do this with any number of spaces (or Tab) as long as you use the same indent for all line in your code.
We indent lines to make it clear which parts belong together. Exactly why we sometimes want to indent lines in our code is something we'll see that now.
If and only if
We can let programs execute difference instructions, different lines of code, depending on whether a certain statement or condition is true or false. For that, we use the keyword if and that's why this is called an if statement
See the following code as an example:
That first line looks familiar, but the second one is new!
if answer == "yes":
We use the special keyword - if - followed by the condition answer == "yes" which means "the variable called answer is exactly equal to "yes". Finally, the line ends with a colon (:).
Only if this condition is true, the indented lines below are executed. In this case, it's the line number 3.
The last line of code, line 4, is not indented and will be executed afterwards regardless of whether the condition is true or false. It is not part of the if-statement because it is not indented.
Try to run the program and enter "yes", and something other than "yes". Be careful to only input small letters! Notice how what the program outputs is different.
That part that follows the keyword "if" is often something, usually a variable, is equal to another value. For comparison we always use exactly two equal signs, as above.
We can also check if a variable is greater or less than another value.
age = int(input("Age? ")) if age > 18: print("You are an adult.")
In this video we look at some examples of if-statements and how to indent code.
- Indentation: Moving code a step to the right. Used in Python to show for example which lines belong to an if statement.
- If statement: The keyword "if" followed by a logic condition allows our program to make decisions.
- Logical condition: A comparison between two values. For example:
age > 18 or name == "marcus".
- Variable: A part of the computer's memory where we can store something, like a piece of text, a name, or a number.