Compound statements contain groups of other statements. They control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line. The if, while and for statements implement traditional control flow constructs.
The if statement is used for conditional execution. If the condition is true, the block under if statement is executed, else the else clause is executed. We can add additional conditions by elif statements.. The elif and else clauses are optional here
Syntax
if expression:
statement(s)
elif expression:
statement(s)
elif expression:
statement(s)
...
else:
statement(s)
Example:
x = 3
if x < 0:
print(x, " is negative")
else:
print(x, " is positive")
x = -4
if x < 0:
print(x, " is negative")
else:
print(x, " is positive")
3 is positive
-4 is negative
For x = 3 , "if x < 0" expression becomes False so statement print(x, " is positive") is executed
For x = -4, "if x < 0" expression becomes True so staement print(x, " is negative") is executed
The while statement is used for repeated execution as long as an expression is true.
Syntax
while expression:
statements
This repeatedly tests the expression and, if it is true, executes the first block. If the expression is false (which may be the first time it is tested) the block which is under else clause, if present, is executed and the loop terminates.
Example:
start = 0
while x < 100:
x = x +2
print(x)
2
4
6
The for statement is used to iterate over the elements of a sequence (such as a string, tuple or list) or other iterable object.
Syntax
for target in iterable:
statement(s)
Example
for i in range(1, 5):
print(i)
1
2
3
4
The in keyword is part of the syntax of the for statement. A for statement can also include an else clause and break and continue.
The break statement, like in C, breaks out of the innermost enclosing for or while loop. Loop statements may have an else clause. It is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
Example
for i in [1, 2, 3, 4, 5]:
if i == 4:
break
print(i)
In the above example the break statement is written for i == 4. so when the value of "i" becomes 4 it executes "break" statement and the control comes out of the loop. So it prints only 1 2 and 3
1
2
3
The continue statement, also borrowed from C, continues with the next iteration of the loop by skipping the rest of the statements of the current loop.
Example:
for i in [1, 2, 3, 4, 5]:
if i == 4:
print("i value is ", i, ".will skip the loop")
continue
print(i)
The loop continues and prints until 3. But when the value of i becomes 4 it will skip the rest of the code i.e. print(i) and jumps to next iteration
1
2
3
i value is 4 .will skip the loop
5