Conditionals
Conditionals
Equals: a == b
Not Equals: a != b
Less than: a < b
Less than or equal to: a <= b
Greater than: a > b
Greater than or equal to: a >= b
These conditions can be used in several ways, most commonly in "if
a = 33
b = 200
if b > a:
print("b is greater than a")
The elif keyword is Python's way of saying "if the previous conditions
were not true, then try this condition"
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
The else keyword catches anything which isn't caught by the preceding
conditions.
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")
© ISBAT UNIVERSITY – 2023. 01/06/2024
You can also have an else without the elif:
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
If you have only one statement to execute, you can put it on the same
line as the if statement.
One line if statement:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
© ISBAT UNIVERSITY – 2023. 01/06/2024
Nested If
if b > a:
pass
while loops
for loops
forever.
forever.
The while loop requires relevant variables to be ready, in this
With the break statement we can stop the loop even if the while
condition is true:
Exit the loop when i is 3:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
With the continue statement we can stop the current iteration, and
continue with the next:
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
With the else statement we can run a block of code once when the
condition no longer is true:
Example
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
© ISBAT UNIVERSITY – 2023. 01/06/2024
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for each
item in a list, tuple, set etc
With the break statement we can stop the loop before it has looped
through all the items:
Exit the loop when x is "banana":
With the continue statement we can stop the current iteration of the
loop, and continue with the next:
Do not print banana:
block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
for loops cannot be empty, but if you for some reason have a for loop
with no content, put in the pass statement to avoid getting an error.
Example