We can use if statements when we want the code to do something when a condition is met.
Sequence of an if statement:
Step 1 | Evaluate condition |
---|---|
Step 2 | • If True , execute action • If False , skip action |
Syntax
x = 3 if x >= 2: print("x is bigger than or equal to 2")
Example
We can use if-else statements when we want the code to do something else if the condition fails.
Sequence of an if-else statement:
Step 1 | Evaluate condition |
---|---|
Step 2 | • If True , execute action • If False , execute another action |
Syntax
x = 30 if x >= 50: print("x bigger than or equals to 50") else: print("x is a number smaller than 50")
Examples
We can use the if-elif-else statement to tell Python to try a different condition if the previous conditions were not met.
Sequence of an if-elif-else statement:
Step 1 | • If the first condition is True , then execute the first action • If it is False , then test for the second condition |
---|---|
Step 2 | • If the second condition is True , then execute the second action • If it is False , execute the final else action |
Syntax
x = 10 if x > 20: print("x is bigger than 10.") elif x = 20: print("x is equals to 20.") else: print("x is neither bigger than 10 or equal to 20.")
Example
1. If - Assign 10 to x. If x is bigger than 0, print "x is a positive number".
2. If-else - Assign -50 to y. If x is bigger than 0, print "x is a positive number". Else, print "x is a negative number".
3. If-elif-else - Assign 0 to z. If x is bigger than 0, print "x is a positive number". Else if x is zero, print "x is 0". Else, print "x is a negative number".
You are expected to comply with University policies and guidelines namely, Appropriate Use of Information Resources Policy, IT Usage Policy and Social Media Policy. Users will be personally liable for any infringement of Copyright and Licensing laws. Unless otherwise stated, all guide content is licensed by CC BY-NC 4.0.