{ }codelper

Learn › Python

Control flow · 08

Booleans and the ternary operator

Keeping true/false in a variable, choosing one of two values, and asking "is it one of these?".

In the Conditions lesson, comparisons were used right inside an if.
This time the result is treated as a value.
The example below reads a day and the visitors' ages, keeps "is it the weekend?" and "is there a child?" in variables, and prints the total of the entry fees: 12 on a weekend, 8 on a weekday.

day = input().strip()ages = list(map(int, input().split())) weekend = day in ("sat", "sun")   # 포함 검사의 결과(참·거짓)를 변수에 담아요child = False                     # 깃발: 아직 어린이를 못 봤어요for age in ages:    if age < 13:        child = True price = 12 if weekend else 8      # 두 값 중 하나를 골라요print("weekend" if weekend else "weekday")print(price * len(ages))print("child" if child else "adults")
stdin
sat
35 41 9
stdout
weekend
36
child

Key points

  • The result of a comparison (age < 13) is a true/false value, a boolean.
    Like a number or a string, you can keep it in a variable and use it many times.
    Use the stored value directly as a condition: if (weekend) is enough, with no == true.
  • A flag is a boolean variable used together with a loop.
    Set it to false before the loop and switch it to true when you meet what you were looking for.
    After the loop it tells you whether there was at least one.
  • The ternary operator chooses one of two values by a condition.
    An if chooses what to do; a ternary chooses a value, so it can sit on the right side of an assignment or inside a print.
  • Use a ternary only when it is short.
    Once you start putting a ternary inside a ternary, writing it out with if and else is easier to read.
  • A membership test asks "is this value one of these?".
    Instead of a long chain of == joined by ||, put the values in a list and ask once whether it is in there.
    The answer is a boolean.
  • Printing a boolean directly differs by language: Python and C# print True, JavaScript, Java and Craykon print true, and C and C++ print 1.
    That is why the example picks a string with a ternary and prints that.

How each language writes it

Pythonweekend = day in ("sat", "sun"); a flag goes from child = False to True.
The ternary is 12 if weekend else 8 — the value for true comes first.
Not is not weekend
JavaScriptconst weekend = ["sat", "sun"].includes(day);; the ternary is weekend ? 12 : 8.
in is not a membership test: "sat" in ["sat", "sun"] is false (it asks about indexes, not values)
TypeScriptSame as JavaScript.
The type is called boolean
Javaboolean weekend = List.of("sat", "sun").contains(day);; the ternary is weekend ? 12 : 8.
To compare with one string, use day.equals("sat")
C#bool weekend = rest.Contains(day); — on an array this needs using System.Linq;.
The ternary is weekend ? 12 : 8
C++bool weekend = std::find(rest.begin(), rest.end(), day) != rest.end(); (<algorithm>); the ternary is weekend ? 12 : 8.
Printing a bool directly gives 1; send std::boolalpha first to get true
CYou need #include <stdbool.h> to use bool, true and false.
There is no membership tool, so loop and check strcmp(day, rest[i]) == 0 one by one.
For a single character: strchr("aeiou", c) != NULL.
The ternary is weekend ? 12 : 8
Craykonweekend = ["sat", "sun"].Contains(day);; a flag goes from child = false; to true.
The ternary is weekend ? 12 : 8.
Strings can be asked too: "aeiou".Contains("e")

Common mistakes

Asking "one of two" with == "sat" or "sun"Python · JavaScript · TypeScript · C · C++ · Craykon

day = "mon"
if day == "sat" or "sun":
    print("weekend")
else:
    print("weekday")

→ weekend — on a Monday. It is read as (day == "sat") or "sun", so when the first part is false, "sun" becomes the condition, and a non-empty string counts as true

Write a comparison on both sides (day == "sat" or day == "sun").
A membership test is shorter (day in ("sat", "sun")).
Java and C# reject this code with a compile error.

Setting the flag back to false in an else

int[] ages = {9, 35, 41};
boolean child = false;
for (int age : ages) {
    if (age < 13) child = true;
    else child = false;
}
System.out.println(child ? "child" : "adults");

→ adults — although there is a 9-year-old. The flag became true at 9 and was overwritten with false at 35 and 41. Written this way, the flag only remembers "is the last visitor a child?". It is the same in every language

Delete the else.
Set the flag to false once before the loop, and inside the loop only ever switch it to true.
Storing a fresh value each lap, as in child = age < 13;, is the same mistake.

A ternary after + without parenthesesJavaScript · TypeScript · Python · C++ · Craykon

const ok = false;
console.log("Result: " + ok ? "yes" : "no");

→ yes — the + is done first. The string "Result: false" becomes the condition, and a non-empty string is always true. Craykon prints yes as well. Python's "Result: " + "yes" if ok else "no" prints only no, and C++'s std::cout << ok ? "yes" : "no"; prints 0

Wrap the whole ternary in parentheses: "Result: " + (ok ? "yes" : "no").
Java and C# report the missing parentheses as a compile error.

How languages differ
Languages split in two when something that is not a boolean is used as a condition.
Java and C# stop it with a compile error.
C, C++, Python, JavaScript, TypeScript and Craykon treat a value like "sun" as true and carry on.
What counts as false also differs by language: an empty list is false in Python but true in JavaScript and Craykon.
That is why the first and third mistakes quietly give a wrong answer.
Making a habit of putting only comparisons or boolean variables in a condition keeps you safe.

Practice