Free preview

100 lessons

Python Done Right

Free preview

Python Done Right · 100 lessons

Learn Python from scratch - syntax through to OOP

No surprise gaps

Actually remember it

Skip what you know

One subscription. All learning paths included.

Our content is best on a larger screen

Conditional logic

The if statement

Explanation

The if statement runs code only when a condition is True:

if condition:
    # indented code runs if condition is True

The indented block (the "body") only executes when the condition evaluates to True. Unindented code runs regardless:

x = 10

if x > 5:
    print("x is greater than 5")  # runs because 10 > 5 is True

if not

Use if not to check when a condition is False:

has_finished_course = False

if not has_finished_course:
    print("Keep going!")  # runs because False becomes True with not

Note: Inside a function, we need double indentation:

def my_function(age):
    if age > 21:
        print("You're over 21!")

Practice questions

4 questions

In the Python Editor, complete the function logic by writing an if statement that assigns the string "C" (for "Credit") to the variable balance_status when the float variable balance is non-negative.

Running the code executes it against a set of test accounts to verify your code and produce a token - what is the token?

Select the correct answer:

+ 3 more questions

Indentation in conditional logic

Explanation

Indentation defines which code belongs to an if statement:

is_active = True

if is_active:
    print("The system is active.")  # indented = part of if block

Be careful - unindented code runs regardless of the condition:

is_birthday = True

if is_birthday:
    print("Happy Birthday!")
print("Let's celebrate!")  # BUG: always runs (not indented)

The second print runs whether is_birthday is True or False.

Practice questions

4 questions

Look at the code in the Python Editor. Which line numbers belong to the if code block and will print when learning_to_program is true?

Select the correct answer:

+ 3 more questions

The else clause

Explanation

The else clause runs when the if condition is False:

if condition:
    # runs when True
else:
    # runs when False

Example:

age = 20
citizen = True

if age >= 18 and citizen:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote.")

Since both conditions are True, the if block runs. If either were False, the else block would run instead.

Note: The else must be at the same indentation level as its if.

Practice questions

4 questions

In the Python Editor, complete the function body by writing an if-else statement to define a new variable, eligible, such that:

  • eligible is true when the integer age is greater than or equal to 18 and the integer income is less than 30000;
  • eligible is false otherwise.

Running the code generates a token the local council can use to validate your logic - what is this token?

Select the correct answer:

+ 3 more questions