If Else
If Else
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"
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
Example :
fruits = ["apple","banana","cherry"]
for x in fruits:
print(x)
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)
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)