Lesson 1 (If statements)
If statements
While Booleans maybe didn't seem that important before, they can be really useful in constructs called "if statements." If statements can allow you to establish instructions throughout your code; they create decision points so that a block of code is only executed if a certain condition is true.
If and else statements
If statements usually contain a conditional statement that can be evaluated as either True or False (Booleans!). In the example above, age >= 18 evaluates to False because we set age to equal 16, while age < 18 evaluates to True. Notice that only the line "Sorry, you cannot vote (yet!)" is printed, as the block of code under the first if statement is never executed because the condition is False.
There are six main operators used in the conditional parts of if statements:
> greater than
< less than
>= greater than or equal to
<= less than or equal to
!= not equal to
== equal to
The reason that this is == instead of = is that we want to evaluate if the two arguments are equal to each other, rather than setting one of them to a new value.
Because a person can only be either right-handed or left-handed, it would be much more efficient to replace the line if handedness != "left": with the command else:.
The importance of whitespace
You might have noticed that statements under the conditional are all indented. This is actually critical to the format of code in Python. See what happens when we don't include the whitespace:
Notice that the error says "expected an indented block." In this case, Python is actually giving a very informative error message, because that is exactly the problem. Also note that the colon : is a critical part of the syntax of the if statement!
Whenever we have a conditional statement (if or else), the command executed below it must be indented. This tells Python which commands are dependent on the if statement and which are not.
In summary, use operations to make conditional statements (e.g. ==), use whitespace to show what you want under control of the if statement.
Elif statements
Sometimes it is better to have more than two conditions so that we can capture more possibilities. To do this, we can use another conditional command called "elif" (short for "else if"), which evaluates only if the preceding if statement is not true. This allows us to make more complicated flowcharts of commands.
Now it's your turn!
Store your eye color in a variable as a string. Then, write an if statement that prints "Your eyes are brown!" if they are brown and prints "Your eyes are not brown!” if they aren’t.
There are lots of other eye colors besides brown, so let's make our solution more comprehensive. Now have an if statement for brown eyes, blue eyes, green eyes, and an "else" statement if none of those colors apply. For each if statement, print "Your eyes are" (the appropriate color).