Professional Documents
Culture Documents
●
if
●
if else
●
elif
●
Nested if
●
loops
if - statement
if statement syntax:
if test expression:
statement(s)
body of if only when test condition is True. If the condition is False, body
of else is executed. Indentation is used to separate the blocks.
Example:
if num >= 0:
print("Positive or Zero")
else:
print("Negative number")
elif
Syntax of if...elif...else:
●
if test expression:
●
Body of if
●
elif test expression:
●
Body of elif
●
else:
●
Body of else
• The elif is short for else if. It allows us to check for multiple expressions.
• If the condition for if is False, it checks the condition of the next elif block
and so on.
• If all the conditions are False, body of else is executed.
• Only one block among the several if...elif...else blocks is executed according
to the condition.
Multiple elif blocks
• The if block can have only one else block. But it can have
multiple elif blocks.
Example:
●
if num > 0:
●
print("Positive number")
●
elif num == 0:
●
print("Zero")
●
else:
●
print("Negative number")
Nested if
Concepts in loops:
– For loop
– While loop
– Nested loops
– Break
– Continue
for loop
for, is often used when we have a piece of code which we want to repeat "n" number of
times.
Example:
for i in range(1,5):
print(i)
Output:
1
2
3
4
Range function iterates i value starting from 1st argument up to but not including 2nd
argument. So i value is iterated only up to 4, but not 5
for loop
The third argument in range function indicates the difference between each number in the
sequence:
Example:
for i in range(1,10,2):
print(i)
Output:
1
3
5
7
9
for loop
Output:
0
-2
-4
-6
-8
for loop
The for loop can also be used to iterate over elements of a sequence such as lists
Example:
computer_brands = ["Apple", "Asus", "Dell", "Samsung"]
for brands in computer_brands:
print(brands)
# prints all the items in list
Example:
for i in range(0,len(computer_brands)):
print(computer_brands[i])
# this is an alternative way of printing all items in a list
while loop
A while loop statement in Python programming language repeatedly
executes a target statement as long as a given condition is true.
Example:
– computer_brands = ["Apple", "Asus", "Dell", "Samsung"]
– i=0
– while i < len(computer_brands):
– print computer_brands(i)
– i=i+1
This reads, as long as the value of the variable i is less than the length of
the list (computer_brands), and prints out each item
Nested loops
Python programming language allows to use one loop inside another loop.
Example:
●
for val in "string":
if val == "i":
break
print(val)
Output:
s
t
r
• If break statement is inside a nested loop (loop inside another loop), break will
terminate the innermost loop.
Continue Statement
The continue statement is used to skip the rest of the code inside a loop for the current
iteration only. Loop does not terminate but continues on with the next iteration.
Example:
for val in "string":
if val == "i":
continue
print(val)
Output:
s
t
r
n
g