Table of Contents:
-
Interpreter executes statements from top to bottom.
-
Function definitions are "digested" for future fuse.
Control Flow: determines order in which statements are executed.
- Conditional Execution.
- Repeated execution - loops.
- Function definitions.
if(condition):
statement_1! # Execute conditionally
statement_2 # Executed in flow, not a part of the if condition- Second condition is executed only if the
conditionis True. - Use uniform indentation to construct body of the conditional.
if(condition):
statement_1
else:
statement_2If condition is True, then statement_1 is executed and if it is not, then statement_2 is executed.
- Numeric value
0is treated asFalse. - Empty sequence,
"",[]is treated asFalse. - Everything else is
True.
if(condition):
statement_1
elif(condition):
statement_2
elif(condition):
statement_3
else:
statement_4- When check is being done for multiple conditions.
elifhelps evaluate multiple conditions and executes the statement within it and then exits the conditional flow.
Repeat something a fixed number of times. Indentation is used for marking the body of the loop.
for i in [1,2,3,5]:
y = y*i
z = i + 1- Fixed loops, do something for a fixed amount of time.
- But usually, there will be cases where looping is required
nnumber of times. - Use
range(0,n). Returns a list of numbers from 0 to n.
for i in range(0,n):
statementswhile(condition):
statements- Execute body if
conditionevaluates toTrue. - After each iteration
conditionis checked again. - Body must ensure loops moves towards termination.