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 = int(input("Please enter an integer: "))
if x < 0:
print("{} is negative".format(x))
elif x % 2 == 0:
print("{} is positive and even".format(x))
else:
print("{} is odd and non-negative".format(x))
Output
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)
Output
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)
Output:
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 n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print("{} equals {}*{}".format(n,x,n//x))
break
else:
# loop fell through without finding a factor
print("{} is a prime number".format(n))
Output:
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 num in range(2, 10):
if num % 2 == 0:
print("Found an even number {}".format(num))
continue
print("Found an odd number {}".format(num))
Output