Conditional and Looping Statements
Conditional Statements
If condition:
It is used to check the logical conditions
Example:
a = 33
b = 200
if b > a:
print("b is greater than a")
In this example we use two variables,a and b, which are used as part of
the if statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print that "b is greater than a"
If..... elif... :
The elif keyword is Python's way of saying "if the previous conditions
were not true, then try this condition"
Example :
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the
elif condition is true, so we print to screen that "a and b are equal".
Else :
The else keyword catches anything which isn't caught by the preceding
conditions
Example :
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen that "a
is greater than b"
You can also have an else without the elif
Example :
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Looping statements
While loop :
With the while loop we can execute a set of statements as long as a
condition is true
Example:
i=1
while i < 6:
print(i)
i += 1
Note: remember to increment i, or else the loop will continue
forever
For loop :
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string)
Example :
fruits = ["apple","banana","cherry"]
for x in fruits:
print(x)
The range() Function
To loop through a set of code a specified number of times, we can use
the range() function,
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and ends at a specified number.
Example :
Method 1:
for x in range(6):
print(x)
# Note that range(6) is not the values of 0 to 6, but the
values 0 to 5
Method 2 :
for x in range(2,6):
print(x)
The range() function defaults to 0 as a starting value, however it is
possible to specify the starting value by adding a parameter: range(2, 6), which means
values from 2 to 6 (but not including 6)
Method 3 :
for x in range(2,30,3):
print(x)
The range() function defaults to increment the sequence by 1, however it is possible
to specify the increment value by adding a third parameter:range(2, 30,3)