Home » Learn Python » Conditions » The “if” Keyword: Conditional Code Execution

The “if” Keyword: Conditional Code Execution

Often we only want to execute some code if a condition is true. The following program only outputs “Hello Bob” if the user enters the password “hello”.

password = input("Enter your password: ")

if password == 'hello':
    print("Hello Bob")

print("Program completed.")
Enter your password: hello
Hello Bob
Program completed.
Enter your password: bingo 
Program completed.


The indentation here is very important. The statement that prints “Hello Bob” is indented four spaces to indicate that it’s controlled by the if statement.

The bit that prints “Program completed” is not indented. It’s not controlled by the if statement, so it always executes.

You can actually use any number of spaces for indenting code blocks in Python. However many you start off using, you must consistently use in the rest of your program.

I recommend using an editor like Visual Studio Code and ensuring it’s configured to turn a tab into four spaces. Then you can use the tab key to indent your code.

Structure of “if” Statements

The general structure of an “if” statement looks like this. Notice the “if” keyword, the condition, a colon, and then an indented code block underneath that.

if [condition]:
    [code to be conditionally executed]

Leave a Reply

Blog at WordPress.com.