TheNewBoston – if else
(skip ahead to 1:14 in video)
Corey Schafer – Conditions and Booleans (Youtube)
LearnPython – Conditions and If
TutorialsPoint – Python if else
Your programs can use logic to decide which branch of code to execute. This makes your code more interesting and flexible, because otherwise it would do the same thing every time.
if
A code block that comes after an “if” statement will only be executed if a condition is true.
(conditions are expressions that are either True or False)
Example:
if x > 7: print('x is more than 7') print('Code blocks are indented.') print('This is not part of the code block.')
In the example, the last line of code prints no matter what x is. The two indented lines only execute when x is greater than 7.
else
If you want something to happen instead when an if statement’s condition is False, you can add an else statement after it.
Else statements do not include a condition.
Example:
if age >= 18: print("old enough to vote") else: print("not old enough to vote yet")
Exactly one of the two print statements will always execute, depending on whether the condition “age>18” is True or False.
Code Block Syntax
if/else logic uses colon and indentation as part of its syntax.
(Go here to read more about colons and indents)
Indented code shows which lines of code are part of a code block.
An indented code block always follows a colon.
If you don’t put an indented line of code after a colon, Python throws an error.
A code block ends when you unindent the next line of code.