xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Conditionals

Basics8 min readLesson 6 of 8

A conditional lets a program choose between paths. Python tests a condition, which produces True or False, and runs an indented block only when the result is True. This is how a program can treat a pass differently from a fail, or show a message only when a password matches.

python
score = 72
if score >= 50:
    print('pass')
else:
    print('try again')
print('report complete')

Output

pass
report complete

6.1 The shape of an if block

An if block starts with the keyword, the condition, and a colon. The next lines are indented, usually by four spaces, and that indentation is part of the syntax.

6.2 Branching further

  • elif runs another test when the first one fails.
  • else catches the remaining case.
  • and requires both tests to hold.
  • or requires either test to hold.

Python stops after the first branch that runs.

python
age = 16
has_ticket = True
if age >= 13 and has_ticket:
    print('entry allowed')
else:
    print('entry denied')

Output

entry allowed

6.3 Common mistake

if mood = 'happy': uses one equals sign and fails as a syntax error. = assigns a value, while == asks whether two values are equal. Keep the indentation consistent inside a block, and remember that the colon belongs to the header line. If a condition is always false, check for a comparison made with the wrong variable or an accidental capital letter.

python
marks = 68
if marks >= 90:
    print('A')
elif marks >= 60:
    print('B')

Output

B

6.4 Practice

  1. Set a marks variable and print a grade with if, elif, and else.
  2. Run it with marks at a boundary such as 60, then with a value below 60.
  3. Add a condition for attendance and use and to decide whether the grade is awarded.

Interview questions

3 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between `=` and `==`?

    `=` assigns a value to a name, and `==` compares two values for equality. Use `==` inside a condition.

  • 02When does Python check an `elif` condition?

    Only when every earlier `if` or `elif` condition in the same chain was false.

  • 03Why does indentation matter in an `if` block?

    Indentation marks the lines that belong to the block. Inconsistent indentation can raise `IndentationError` or put a line outside the branch by mistake.