2nd Class - Control Structures
2nd Class - Control Structures
for
if / elif / else
while
Syntax: Syntax:
if condition: for VariableName in ObjectName / range( ):
--statements-- --statements--
elif condition:
--statements-- Syntax:
else: while condition:
--statements-- --statements--
Executions of Controls Structures
if / elif / else: Note: A if block can have multiple elif block, but it should have only one else
block.
if
True
conditio Example:
n a = 200
Output
Fals b = 33
elif
e
conditio True
if b > a:
n print("b is greater than a")
Output elif a == b:
Fals print("a and b are equal")
e else:
else print("a is greater than b")
Output
Executions of Controls Structures……
for
Compiler Enters into
1
Object
Name
2 Assigns All Values to
No
in
Yes
4
3
Finds Assigns Next
Assign 1st Values to
Next Value
Value Variabl
e
Output
for - Examples Output:
• To loop through a set of code a specified number of times, we can use Example: 0
the range( ) function, for a in range(4) 12
• The range( ) function returns a sequence of numbers, starting from 0 by : 3
default, and increments by 1 (by default), and ends at a specified number. Note: print(a)
that range(4) is not the values of 0 to 4, but
the values 0 to 3.
FOR loop inside another FOR loop is called Nested FOR loop.
Outer FOR is considered as Main Loop and Inner FOR is considered as Sub
Loops.
When the Main Loop condition gets true, then compiler enters into sub loop and
executed continuously in the sub loop until sub loop condition gets failed.
After sub loop condition gets failed, then compiler will return back to Main Loop.
When the Main Loop condition gets failed, then compiler displays the output.
Note: Whenever the compiler enters into Sub Loop, then the sub loop will start
from it’s initial value.
while Example:
break
We can stop the loop before it has looped through all the elements.
Note: We can execute a set of i = 1 Output: continue
1
statements as long as a while i < 4: 2
We can stop the current iteration of the loop, and continue with the
print(i) next
condition is true. 3
Example:
Pass Example: for a in
for a in range(6): Output: Output:
0 for a in range(6): range(4):
print(a) 0
1 print(a) if a == 2: 1
if a == 2: 2 3
if a == 2:
break; continue
pass
print(a)
Example: i = 0
print(“Hello”)
i = 1
while i < 4: Output:
while i < 6: Output:
print(i) 1
i += 1 1
2
if i == 3: 2 if i == 3: 4
3
break continue
i += 1 print(i)
FAQ: