-
Python Loops
If you want to iterate through all the elements of a list or a dictionary, python lets you do this with two primitive loop commands:- while loops
- for loops
The while LoopWithin the while loop, as long as a condition is true, the set of statements are executed
Example
Print x as long as count is less than 5:
count = 1
while count < 6:
print(count)
count += 1The for Loop
A for loop is used for iterating over a sequence (i.e a list, a tuple, a dictionary, a set, or a string).
Example1: Print each fruit in a fruit list:
fruits = [“apple”, “banana”, “kiwi”]
for x in fruits:
print(x)
Example2: Print all the keys in a dictionary:
report={“subject”:”Maths”, “grade”: “A”,”marks”:99}for x in report:print(x)
Example3: Print all the valuess in a dictionary:report={“subject”:”Maths”, “grade”: “A”,”marks”:99}for x in report.values():print(x)Conditions – If … Else
You would use several conditions in your programming. Python supports the usual logical conditions from mathematics:
- 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 statements” and loops.
An “if statement” is written by using the if keyword, “else statement” by else keyword
Example:
a = 45
b = 33if b > a:
print(“b is greater than a”)
else
print(“b is not greater than a”)elif condition (elseif)
Example:
a = 85
b = 63if b > a:
print(“b is greater than a”)
elif b==a:
print(“b is equals to a”)
else
print(“b is less than a”)The break statement
With the break statement we can stop the loop even if the while condition is trueExample
Exit the loop when x is 3:
x = 1
while x < 5:
print(x)
if x == 3:
break
x += 1The continue statement
This will print 1,2,4,5,6. if the i == 3, the continue of the loop will be invoked skipping the print of 3
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)