Professional Documents
Culture Documents
Module 5 - Conditional Statementscontrol Structures
Module 5 - Conditional Statementscontrol Structures
statements/Control Structures
Module 5: Conditional statements/
Control Structures
www.cognixia.com
www.cognixia.com
Module 5: Conditional statements/Control Structures
If Statements
While construct
For Statements
Looping Techniques over List, dictionary
The range() Function
Break and continue Statements
Pass Statements
o Switch statement
Module 5: Conditional statements/Control Structures
If Statements
What is an if statement?
An if statement tests for a condition, and then responds to that condition. If the condition is true, then
whatever action is listed next gets carried out. You can test for multiple conditions at the same time,
and respond appropriately to each condition.
if statement
if..else statements
nested if statements
if-elif ladder
Module 5: Conditional statements/Control Structures
If Statements if expression:
statement(s)
The syntax of the if statement is:
The syntax of the if...elif statement is:
if expression:
if expression1:
statement(s) statement(s)
statement(s) else:
statement(s)
else:
statement(s)
Module 5: Conditional statements/Control Structures
While Loop
What is while loop in Python?
The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.
We generally use this loop when we don't know beforehand, the number of times to
iterate.
Python interprets any non-zero value as True. None and 0 are interpreted as False.
Syntax of while Loop in Python n = int(input("Enter n: ")) n while loop with else
while test_expression: = 10 sum = 0 i = 1 while i while test_expression:
<= n: Body of while
Body of while sum = sum + i Else:
i = i+1 body of while failed
print("The sum
is", sum)
Module 5: Conditional statements/Control Structures
For Loop
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called
traversal.
Example:
Syntax of for Loop
languages = ["C", "C++", "Perl", "Python"] for
for iterator_var in sequence:
x in languages:
statements(s) print(x)
Here, iterator_var is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the
code using indentation.
Module 5: Conditional statements/Control Structures
For an argument n, the function returns integer values from 0 to n-1. range(stop)
b. Two Parameters
Finally, the range() function can also take a third parameter. This is for the interval. range(start,stop,interval)
for i in range(1,10,0):
print(i)
for i in range(1,10,0):
= x + 10 continue else: