We have already seen conditional expressions in the context of while
loops. Conditional expressions can be used with if
statements to allow a program to make decisions while it is running. There are numerous applications for if
statements. For example, they can be used to detect invalid values and prevent errors:
input_value = 1e99 if input_value > 1e10: print("Warning: invalid parameter detected.") else: print("--- Start of iteration ---")
The general syntax for an if statement is the following:
if conditional_expression: statements else: statements
The else
clause is optional. Python doesn't have a switch
statement for choosing between multiple values. Instead, it has a special keyword called elif
, which is a contraction of "else if." This can be used to emulate a switch
statement. For example, we can use if
with elif
to choose an algorithm based on user input:
solution_type = "numerical" if solution_type == "analytical": print...