PyPython Lab

Stage 1 · 25 minutes · Free

Conditionals: if / elif / else

Let a program decide: comparisons, if, elif, else, and/or/not operators and indentation rules.

Objectives

Why learn this

A smart program must branch: enough points means pass, too few means fail; the right password gets in, the wrong one gets an error.

Concept

if dieu_kien: runs the indented block below when the condition is true.

elif (else if) checks the next condition when the earlier ones are false. else runs when all are false. Python stops at the FIRST true branch.

Comparison uses ==, while = is assignment. Combine conditions: and (both true), or (one of them true), not (negation).

After the : you must go to a new line and indent 4 spaces. Lines in the same block must be indented equally.

Syntax

if dieu_kien_1:
    lenh
elif dieu_kien_2:
    lenh
else:
    lenh

Example

diem = float(input())
if diem >= 8:
    print("Giỏi")
elif diem >= 5:
    print("Đạt")
else:
    print("Chưa đạt")

Input data:

6.5

Output:

Đạt

Line-by-line walkthrough

  1. Line 1: read the score 6.5.
  2. Line 2: 6.5 >= 8 is false, skip line 3.
  3. Line 4: 6.5 >= 5 is true, run line 5 printing Đạt.
  4. Lines 6-7: do not run, because a branch was already true.

Common mistakes

if x = 5:

= is assignment; comparison must use ==.

if x == 5:
if x > 3
    print(x)

Missing the colon at the end of the if line.

if x > 3:
if x > 3:
print(x)

The block after if must be indented: IndentationError.

Thêm 4 dấu cách trước print(x).

Summary

Practice 2 exercises and 3 quick questions

Write code right in the browser; the grader runs real Python and points to the exact wrong line.

Practice free