Which of these logic constructs most
efficiently (in terms of code conciseness and variable reuse) allows
you to select and execute one code block out of 3 or more based on the
value of a single variable?
EXPLANATION
if
statement
People make decisions on a daily basis. What should I have for lunch?
What should I do this weekend? Every time you make a decision you base
it on some criterion. For example, you might decide what to have for
lunch based on your mood at the time, or whether you are on some kind of
diet. After making this decision, you act on it. Thus decision-making
is a two step process – first deciding what to do based on a criterion,
and secondly taking an action.
Decision-making by a computer is based on the same two-step process. In Python, decisions are made with the
if
statement, also known as the selection statement. When processing an
if
statement, the computer first evaluates some criterion or condition.
If it is met, the specified action is performed. Here is the syntax for
the
if
statement:
When it reaches an
if
statement, the computer only executes the body of the statement only if
the condition is true. Here is an example in Python, with a
corresponding flowchart:
if age < 18:
print("Cannot vote")