0% found this document useful (0 votes)
3 views

Python if Else

The document explains Python's conditional statements, including 'if', 'elif', and 'else', which allow for decision-making in code. It also covers logical operators such as 'and', 'or', and 'not', as well as the concept of nested if statements. Additionally, it mentions the use of the 'pass' statement to handle empty if statements without causing errors.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python if Else

The document explains Python's conditional statements, including 'if', 'elif', and 'else', which allow for decision-making in code. It also covers logical operators such as 'and', 'or', and 'not', as well as the concept of nested if statements. Additionally, it mentions the use of the 'pass' statement to handle empty if statements without causing errors.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Python Conditions &

If statements
An "if statement" is written by using the if keyword.

a = 33
b = 200
if b > a:
print("b is greater than a")

Indentation: Python relies on indentation (whitespace at the beginning of a line)


to define scope in the code.

a = 33 a = 33
b = 200 b = 200
if b > a: if b > a:
print("b is greater than a") print("b is greater than a")
Elif

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 is not caught by the preceding
conditions.

a = 200 a = 200
b = 33 b = 33
if b > a: if b > a:
print("b is greater than a") print("b is greater than a")

elif a == b: else:

print("a and b are equal") print("b is not greater than a")

else:
print("a is greater than b")
The and keyword is a logical operator, and is used to combine conditional
statements:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
The or keyword is a logical operator, and is used to combine conditional
statements:

a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
The not keyword is a logical operator, and is used to reverse the result of the
conditional statement:

x = True
print(not x)
You can have if statements inside if statements, this is called nested if statements

x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.

a = 33
b = 200
if b > a:
pass

You might also like