You learn to make your programs take decisions with if, elif, else, and logical operators.
Open this lesson in KodokonA program often has to choose between several paths. The if keyword runs a block of instructions only if a condition is true. A condition is an expression that evaluates to True or False. The if line ends with a colon :, and the block that follows is indented by 4 spaces: this indentation tells Python which lines belong to the block.
age = 20
if age >= 18:
print("You are an adult.")Conditions are written with comparison operators: == (equal to), != (not equal to), < (less than), > (greater than), <= and >=. To chain several cases, add elif ("else if") which tests another condition, then else ("otherwise") which runs when everything else is false.
temperature = 15
if temperature > 25:
print("It's hot.")
elif temperature > 10:
print("It's mild.")
else:
print("It's cold.")To combine several conditions, use the logical operators: and (true if both conditions are true), or (true if at least one is true), and not (inverts the result: not True is False).
age = 30
has_ticket = True
if age >= 18 and has_ticket:
print("Entry allowed.")
if not has_ticket:
print("Ticket missing.")else block run?True and False evaluate to?