Conditions and Loops in Python
What if you want to do some specific tasks when the string is "Python" and some other tasks when the string is "Java". To achieve this conditioning we can use conditional statements in python or any other language. When we want to do some task for n number of times or we want to loop through some specific list, we can use different types of loops in this kind of situation.
Conditional Statements in Python
In python, we have two types of conditional statements.
- If-else
- if-elif-else (if - else if - else)
Both conditional statements seem almost similar, and actually, they are. There is just a minor difference between these two statements. We will understand this difference using code examples. If you know any other language(s), you might be wondering if python has a switch case or not. NO, python does not have a switch case.
if-else
Syntax:
if(conditional expresson):
statement
else:
statement
If I have explained the if-else statement in plain English then it would be the "either this or that" statement.
Let's assume if the string is java, I want to do the sum of two numbers else I want to multiply two numbers.
num1 = 5
num2 = 2
lang = 'java'
if(lang=="java"): # check if value of lang variable is 'java'
c = num1 + num2
print(c)
else:
c = num1 * num2
print(c)
# OUTPUT: 7
num1 = 5
num2 = 2
lang = 'java'
if(lang!="java"): # check if value of lang variable is NOT 'java'
c = num1 + num2
print(c)
else:
c = num1 * num2
print(c)
# OUTPUT: 10
It is not compulsory to use else part. You can use only if part as well. For example, add the string "Programming" to the existing string if it is "Python" or does nothing.
lang = 'Python'
if(lang=="Python"):
lang = lang +" Programming"
print(lang)
# Output: Python Programming
lang = 'Java'
if(lang=="Python"):
lang = lang +" Programming"
print(lang)
# Output: Java
Sometimes, you can go into the if statement using only variable as well. For example,
lang = 'Python'
if(0):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python
lang = 'Python'
if(1):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python Programming
lang = 'Python'
if(True):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python Programming
lang = 'Python'
if(False):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python
lang = 'Python'
if(""):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python
lang = 'Python'
if("random string"):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python Programming
lang = 'Python'
if(None):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python
lang = 'Python'
if([1]):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python Programming
lang = 'Python'
if([]):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python
lang = 'Python'
if({'a':1}):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python Programming
lang = 'Python'
if({}):
lang = lang +" Programming"
print(lang)
# OUTPUT: Python
If we want to combine multiple conditions we can use and and or within the if statement.
lang = 'PYTHON'
if(lang.isupper() and len(lang) > 2):
print("Worked!")
# OUTPUT: Worked!
if(lang.islower() or len(lang) == 6):
print("Worked again!")
# OUPUT: Worked again!
if-elif-else
Syntax:
if(conditional expresson):
statement
elif(conditional expresson):
statement
else:
statement
We use this conditional statement when we want to test more than one scenario. Let's understand this by an example.
marks = 75
if(marks >= 34 and marks <= 50):
print("Grade C!")
elif(marks > 50 and marks <= 75):
print("Grade B!")
elif(marks > 75 and marks <= 100):
print("Grade A!")
elif(marks >= 0 and marks < 34):
print("FAIL!")
else:
print("Something is wrong!")
# OUTPUT: Grade A!
Be aware when you use multiple if and if-elif. A single error in your logic and all your code-base can throw an error. To understand this, see the below example.
marks = 75
if(marks > 75 and marks <= 100):
print("Grade A!")
elif(marks > 50):
print("Grade B!")
elif(marks >=34):
print("Grade C!")
else:
print("Something is wrong!")
print("-----------------------------------")
marks = 75
if(marks > 75 and marks <= 100):
print("Grade A!")
if(marks > 50):
print("Grade B!")
if(marks >=34):
print("Grade C!")
""" OUTPUT:
Grade B!
-----------------------------------
Grade B!
Grade C!
"""
Loops in Python
In python, we have two kinds of loops.
- for Loop
- while Loop
- Loop Control Statements
for Loop in Python
Syntax:
for iterator in sequence:
statement(s)
For loop is used when we want to traverse through the sequential datatype. For example traversing through lists, tuples, strings etc.
fruits = ['apple', 'banana', 'mango', 'grapes', 'peach']
for fruit in fruits:
print(fruit)
""" OUTPUT:
apple
banana
mango
grapes
peach
"""
for i in range(len(fruits)):
print(fruits[I])
""" OUTPUT:
apple
banana
mango
grapes
peach
"""
In the first example above, in the fruit variable, we are directly getting each element of the fruits list. Whereas, in the second example, we are accessing each element by index reference. The range(n) function returns a sequence of numbers. Syntax: range(start, stop, step)
.
for i in range(2, 13, 3):
print(i)
""" OUTPUT:
2
5
8
11
"""
We can use for loop with dictionaries as well.
dict1 = {"lang": "python", "year": "2021", "month": "november"}
for item in dict1:
print(item, ":" , dict1[item])
""" OUTPUT:
lang : python
year : 2021
month : november
"""
while Loop in Python
Syntax:
while expression:
statement(s)
When you need to do some work repeatedly until some condition satisfies, in that situation you can use a while loop.
Let's assume we need to print "Hello World" until the count variable became 5.
count = 0
while (count < 5):
print("Hello World")
count = count + 1
Loop Control Statements
There are times when you need to break the loop or skip some iterations in the loop or do nothing. This kind of thing can be done using Loop Control Statements. In python, we have three looping control statements.
- Break statement
- Continue statement
- Pass statement
We use a break statement when we want to break the loop when certain conditions match. For example,
fruits = ['apple', 'banana', 'mango', 'grapes', 'peach']
for fruit in fruits:
if(fruit == 'mango'):
break
print(fruit)
""" OUTPUT:
apple
banana
"""
While the break statement breaks the loop, the continue statement makes the loop skip the current iteration and forces it to go to the next iteration.
fruits = ['apple', 'banana', 'mango', 'grapes', 'peach']
for fruit in fruits:
if(fruit == 'mango'):
continue
print(fruit)
""" OUTPUT:
apple
banana
grapes
peach
"""
Pass statement is a meaningless piece of code that suggests the interpreter to do nothing. It is similar to the comment but comments are ignored by interpreters while the pass statement executed by the interpreter and as per the name does nothing. Pass statement is used with function and class as well, which I will explain in the next section.
fruits = ['apple', 'banana', 'mango', 'grapes', 'peach']
for fruit in fruits:
if(fruit == 'mango'):
pass
print(fruit)
""" OUTPUT:
apple
banana
mango
grapes
peach
"""
for...else & while...else
During the development journey, there are times when you might need to use for..else and while...else. These are just normal for and while loop with special else cases. Let's see an example to understand it.
fruits = ['apple', 'banana', 'mango', 'grapes', 'peach']
for fruit in fruits:
if(fruit == 'mango'):
break
print(fruit)
else:
print("Loop Did Not Break!")
""" OUTPUT:
apple
banana
"""
fruits = ['apple', 'banana', 'mango', 'grapes', 'peach']
for fruit in fruits:
if(fruit == 'abc'):
break
print(fruit)
else:
print("Loop Did Not Break!")
""" OUTPUT:
apple
banana
mango
grapes
peach
Loop Did Not Break!
"""
So, you might have guessed. When the loop does not break OR the loop completes all the iterations without interruption, else block is executed. The same happens with the while loop as well.
i = 1
while i < 6:
if(i == 3):
break
print(i)
i += 1
else:
print("All iterations of While are executed successfully.")
""" OUTPUT:
1
2
"""
Conclusion
Finally! We are at the end of this section 😁.
I know, it is a lot to take in at a time. But, you don't need to remember everything that I have mentioned here. I just showed you so that you can recall what is possible and what is not. There are some other methods as well that I have not mentioned here.
If you want to find out more about control statements and loops in python, check out Programiz.
That was it. Thank you for reading.
Let me know if you need any help or want to discuss something. Reach out to me on Twitter or LinkedIn. Make sure to share any thoughts, questions, or concerns. I would love to see them.
Till the next time 👋