Control Flow Statements
1. Explain if
statements.
if
statement is used to execute a block of code only if a specified condition is true.
2. Explain elif
statements.
elif
statement is used to check additional conditions if the preceding if
condition is false.
3. Explain else
statements.
else
statement is used to execute a block of code when none of the preceding conditions are true.
4. Explain the key difference between if
and elif
when combining control flow statements together.
The key difference is that elif
will only be executed if the previous conditions are not met (False
). Whereas if
will continue to evaluate even if the previous condition is met (True
).
# if -> if
a = 2
if a > 1:
a += 1
if a > 2:
a +=1
a # 4
# if -> elif
a = 2
if a > 1:
a += 1
elif a > 2:
a +=1
a # 3
In the first example, a
returns 4 because both if
are evaluated to be true so they were executed. Whereas the second example, the a returns 3
because elif
will only execute if the previous condition is false.
5. Describe for
loop statements and the main use case.
The for
loop is used to iterate over a sequence (such as a list, a tuple, or a set) and execute a block of code for each item in the sequence.
Use case: for
loops are often used when you know the number of iterations beforehand, such as iterating over elements in a sequence.
6. Provide the for
loop general syntax and explain the components.
for <var> in <iterable>:
<statement(s)>
var
: variable that takes the value of each item inside the sequence on each iteration.iterable
: collection of objects in a sequence (inbuilt function-range/random or list).statement(s)
: actions to be evaluated/performed for each value at the end of each iteration.
7. Describe while
loop statements and the common use case.
The while
loop is used to repeatedly execute a block of code as long as a specified condition is true.
Use case: while
loops are used when the number of iterations is not known and is determined by a condition.
8. Provide the while
loop general syntax and explain the components.
while <condition>:
<statement(s)>
condition
: The condition to evaluate whether to stay within the loop. If the condition is evaluated to beFalse
, the loop will stop.statement(s)
: actions to be evaluated/performed for each value at the end of each iteration.
9. Describe break
statements.
break
statement is encountered, it will immediately exit the loop’s clause.
10. Describe continue
statements.
continue
statement is encountered, it will skip the rest of the code inside a loop for the current iteration and move to the next iteration.