By reading this article your following problems will be answered.
Conditionals in Python.
How to use ‘if’ condition in Python.
How to use conditions inside loops in Python.
If Condition in Python
- In python the ‘if’ condition can be used as following.
- In Python, when two values are comparing to be equal, the symbol ‘==’ is used rather than ‘=’.
- This is because the ‘=’ is used to set variables and to differentiate from setting a variable.
varAge = 20
if varAge > 17:
varCategory = "Adult"
else:
varCategory = "Child"
Elif in Python
- The ‘elif’ function works as else if.
- That means if the first criteria does not met, then a second criteria or another if condition will be checked.
- There can be any number of ‘elif’ conditions following an ‘if’.
- At the end of the sequence of conditions ‘else’ is used and the code under ‘else’ runs only if any of the previous conditions are not met.
- The following code shows how to use an ‘elif’ function.
varTitle = "Mr"
if varTitle == "Mr":
varCategory = "Male adult"
elif varTitle == "Ms":
varCategory = "Female"
elif varTitle == "Mrs":
varCategory = "Female"
elif varTitle == "Master":
varCategory = "Male child"
else:
varCategory = "N/A"
Conditions in loops in Python
- Conditions can also be used inside loops.
wallet = 25
for price in range(5):
if price >= price:
wallet = wallet - price
print("Now I have",wallet)
print("Final amount:",wallet)
Additional points about conditionals in Python
- An ‘if’ condition doesn’t always require an ‘else’.