basforge

Search titles, text and the “If it doesn’t work” cases.

    RU

    Conditions in Python: if, elif and what counts as false

    if runs a block only when the condition is true; elif and else when it isn’t. A condition can be any value: a comparison gives True or False, and an empty string, zero and None count as false. Write a disk check that says whether it’s time to clean up, and see why if x == 1 or 2 is always true.

    What you’ll get

    A disk check: how much is used and what to do about it.

    # disk_check.py
    import shutil
    
    disk = shutil.disk_usage("C:/")
    used_pct = disk.used / disk.total * 100
    
    if used_pct >= 90:
        print(f"{used_pct:.0f}% used — the disk is almost full")
    elif used_pct >= 75:
        print(f"{used_pct:.0f}% used — time to clean up")
    else:
        print(f"{used_pct:.0f}% used — plenty of space")
    python disk_check.py
    # 90% used — time to clean up

    shutil.disk_usage is a standard library module: it returns the disk’s size, used and free space in bytes. On Linux and macOS write "/" instead of "C:/". In the example 89.7% is used: the f-string rounded it to 90 for display, while if compared the exact number — hence “time to clean up” rather than “almost full”.

    What will it print?
    if "0":
        print("yes")
    else:
        print("no")
    What will it print?
    Answer:
    yes

    Any value can be a condition. A string is false only when it’s empty: "". "0" has one character, so it’s true — that it’s the digit zero doesn’t matter to Python.

    How it works: checked top to bottom, one block runs

    Python checks the conditions in order and runs the block of the first true one, skipping the rest — even if they’re true too. So put the strictest first: >= 90 before >= 75. The other way round, 95% would land in “time to clean up”.

    if condition:        # true — run the block below, look no further
        ...
    elif other:          # any number of elif, including none
        ...
    else:                # nothing matched; else is optional
        ...

    A block is the lines indented 4 spaces under a line with a colon. When the indentation ends, the block ends.

    Comparisons and logic

    Code What it means
    ==, != equal, not equal; 1 == 1.0 is True, "5" == 5 is False
    <, >, <=, >= less, greater; strings compare alphabetically, and "10" < "9" is True
    75 <= x < 90 two comparisons at once — as in math
    and, or, not and, or, not: x > 50 and x < 100
    in a piece of a string: "ERROR" in line
    is None a check specifically for None: if result is None:

    Strings compare alphabetically character by character: "10" < "9" because "1" comes before "9". Compare numbers from text after int().

    What Python counts as false

    A condition doesn’t have to be a comparison: if name: checks the value itself.

    False True
    False, None True
    0, 0.0 any other number, -1 included
    "" — an empty string any non-empty one: "0", " ", "False"
    empty collections — in the “Lists and tuples” chapter non-empty ones

    Hence a short input check: if not answer.strip(): — nothing but spaces was typed.

    Picking one of two values fits on one line: kind = "ssh" if port == 22 else "other". It reads like a sentence; for longer logic, use a regular if.

    Take it further

    Is it a leap year

    Divisible by 4 and not by 100 — or divisible by 400. The remainder is %; join with and and or.

    year = 2100
    if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        print("leap year")
    else:
        print("common year")
    # common year
    A password passes: at least 12 characters and not all digits

    Length is len(), all digits is isdigit(); join the conditions with and and not.

    password = input("Password: ")
    if len(password) >= 12 and not password.isdigit():
        print("acceptable")
    else:
        print("too short or all digits")
    “yes”, “Yes ” and “y” mean agreement, anything else is a refusal

    Trim spaces and lowercase once, into a variable — then compare with or.

    answer = input("Continue? ").strip().lower()
    if answer == "yes" or answer == "y":
        print("continuing")
    else:
        print("cancelled")

    If it doesn’t work

    SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

    Cause
    The condition has a single =: if x = 5:. One = is assignment; comparison is two.
    Fix
    Write if x == 5:.

    SyntaxError: expected ':'

    Cause
    No colon at the end of the line with if, elif or else.
    Fix
    Add the : — after it Python expects an indented block.

    IndentationError: expected an indented block after 'if' statement on line 2

    Cause
    The line under if isn’t indented: Python uses indentation to tell what belongs to the block.
    Fix
    Indent the block 4 spaces. Don’t mix spaces and tabs in one file — an editor with Python highlighting inserts spaces itself.

    The condition fires no matter what’s in x

    Cause
    You wrote if x == 1 or 2:. Python reads it as (x == 1) or 2, and 2 isn’t zero, so it’s true.
    Fix
    Compare with each value: if x == 1 or x == 2:.

    Typed 5, and if answer == 5: doesn’t fire

    Cause
    input() returns a string: "5" == 5 is False; a string and a number aren’t equal.
    Fix
    Convert the input to a number — int(input(…)) — or compare with a string: answer == "5".