Tingimuslause

Tingimuslausega saab kontrollida, kas mingit osa koodist käivitatakse.

Python

Java

Lihtne tingimuslause

if boolean_condition:
    do_something_if_true()
if (booleanCondition) {
    doSomethingIfTrue();
}

if-else

if boolean_condition:
    do_something_if_true()
else:
    do_something_else()
if (booleanCondition) {
    doSomethingIfTrue();
} else {
    doSomethingElse();
}

if-elseif-else

if boolean_condition:
    do_something_if_true()
elif some_other_condition:
    do_some_other_thing()
else:
    do_something_else()
if (booleanCondition) {
    doSomethingIfTrue();
} else if (otherCondition) {
    doSomeOtherThing();
} else {
    doSomethingElse();
}

Pikem if-elseif-elseif-else jada (switch-case)

month = 2

match month:
    case 1:
        month_string = "January"
        break
    case 2:
        month_string = "February"
        break
    case 3:
        month_string = "March"
        break
    case 4:
        month_string = "April"
        break
    case _:
        month_string = "Invalid"
        break

    print(month_string)
int month = 2;
String monthString;

switch (month) {
    case 1:
        monthString = "January";
        break;
    case 2:
        monthString = "February";
        break;
    case 3:
        monthString = "March";
        break;
    case 4:
        monthString = "April";
        break;
    default:
        monthString = "Invalid";
        break;
}

System.out.println(monthString);

Ternary operator

>>> "true" if True else "false"
'true'
>>> 'true' if False else 'false'
'false'
jshell> true ? "true" : "false"
$1 ==> "true"
jshell> false ? "true" : "false"
$2 ==> "false"

Tõeväärtus

True

true

False

false

Tingimus

a and b

a && b

a or b

a || b

not a

!a