Chuyển đến nội dung chính
eLearner.app
Mô-đun 1 · Bài học 3 trong tổng số 43/36 trong khóa học~10 min
Bài học theo mô-đun (3/4)

Điều kiện: if, elif, else

Conditionals let you run different code based on the value of a boolean expression. In Python they are written with if, elif (shorthand for "else if") and else.

The basic form

Python
eta = 18
if eta >= 18:
    messaggio = "maggiorenne"
else:
    messaggio = "minorenne"

Notice:

  • after the condition there's always a colon :;
  • the block "inside" the if is identified by indentation (4 spaces);
  • you don't need parentheses around the condition (although they are allowed).

More branches with elif

Python
voto = 7
if voto >= 9:
    giudizio = "ottimo"
elif voto >= 7:
    giudizio = "buono"
elif voto >= 6:
    giudizio = "sufficiente"
else:
    giudizio = "insufficiente"

The elif branches are evaluated in the order you write them and they stop at the first one that turns out to be true.

Conditional expression (ternary)

For simple cases you can write everything on one line:

Python
eta = 20
messaggio = "maggiorenne" if eta >= 18 else "minorenne"

It reads naturally in English: "maggiorenne if eta >= 18 else minorenne".

"Truthy" / "falsy" values

A condition doesn't have to be a comparison: any value can be used as a condition. These are considered false: False, None, 0, "", [], {}. Everything else is true.

Python
nome = "Ada"
if nome:
    saluto = f"Ciao {nome}!"
else:
    saluto = "Ciao sconosciuto!"

Conditional expressions (ternary operator)

Python supports a compact single-line if-else construct, which acts as the ternary operator found in other languages:

Python
result = "Even" if n % 2 == 0 else "Odd"

This keeps your code concise when you simply need to assign a value based on a condition.

Try it yourself

tập thể dục#python.m1.l3.e1
Nỗ lực: 0Đang tải…

Given `number = 15`, assign to `sign` the string 'positivo' if the number is > 0, 'zero' if it is 0, 'negativo' otherwise. Evaluate `sign`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Three branches: > 0, == 0, else.

Giải pháp khả dụng sau 3 lần thử

Review exercise

tập thể dục#python.m1.l3.e2
Nỗ lực: 0Đang tải…

Given `age = 20`, assign to `category` the string 'maggiorenne' or 'minorenne' using the ternary expression (if/else on one line).

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Syntax: value_if_true if condition else value_if_false

Giải pháp khả dụng sau 3 lần thử

Additional challenge

tập thể dục#python.m1.l3.e3
Nỗ lực: 0Đang tải…

Write a conditional structure that checks if the variable `x` (initialized to `-5`) is greater than 0, less than 0, or equal to 0. Assign the string `'positive'`, `'negative'`, or `'zero'` to `sign` accordingly. Finally, evaluate `sign`.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use if x > 0:, elif x < 0:, and else: to handle the three cases.

Giải pháp khả dụng sau 3 lần thử