Back to Course

Introduction to Python

0% Complete
0/0 Steps
  1. Python: Basics
    14Topics
    |
    15 Quizzes
  2. Python: Control Flow
    12Topics
    |
    12 Quizzes
  3. Python: Errors
    5Topics
    |
    5 Quizzes
Lesson 2, Topic 4
In Progress

Python: If Statements

Yasin Cakal 11 Oct 2021
Lesson Progress
0% Complete

Now that you learned about boolean variables (True and False), we can start with the if statement. It is critical to understand boolean variables and expressions because they serve as the building blocks for conditional statements.

The “if” is a conditional statement that checks if the statement is True and executes the code following the : colon. Let’s take a look at some examples:

if True:
    print("This will print.")
if False:
    print("This will not print!")

Before we go on, there are essential aspects of Python programming that we must go over. First, if you forget the : colon, Python will throw a SyntaxError. Second, notice that the print function is indented by a tab or 4 spaces (tab usually equals 4 spaces). If you forget to indent the code following the : colon, you will get an IndentationError. Lastly, don’t forget to indent all lines of code that should be in the if statement, or it will be executed as if it is not in the if statement. Here is an example:

if False:
    print("This will not print.")
    print("This will not print either.")
print("But this will print!")

Now let’s take a look at a more practical example:

password = 1234

# Let's check the password.
if password == 1234:
    print("You logged in!") # This will print.
if password != 1234:
    print("Incorrect password!") # This will not!

# What if the password was wrong?
<meta charset="utf-8">password = 4321

# Let's check the password.
if password == 1234:
    print("You logged in!") # This will not print.
if password != 1234:
    print("Incorrect password!") # But this will!

Congratulations, now you learned how to write code that makes decisions on your behalf!

%d bloggers like this: