while
loopA while loop will continuously execute code depending on the value of a condition. It begins with the keyword while, followed by a comparison to be evaluated, then a colon. On the next line is the code block to be executed, indented to the right. Similar to an if
statement, the code in the body will only be executed if the comparison is evaluated to be true. What sets a while loop apart, however, is that this code block will keep executing as long as the evaluation statement is true. Once the statement is no longer true, the loop exits and the next line of code will be executed.
A while loop executes the body of the loop while a specified condition remains True.
They are commonly used when there’s an unknown number of operations to be performed, and a condition needs to be checked at each iteration
Common bugs related with while loop
number = 1
while (number < 4):
print(" number is : ", number)
number = number + 1
for
loopfor
loop is used when we want to loop through list of things, list of words, list of numbers, lines in file etc (In pyton terms, It could be list, tuple, set or string)
for x in range(5,10):
print(x)
days = ['monday','tuesday','wednesday','thursday','friday','saturday','sunday']
for day in days:
print(day)
for index, fruit in enumerate(days):
print(index, fruit)
animals = ('elephant', 'bear', 'bunny', 'dog', 'cat', 'velociraptor' )
for animal in animals:
print(animal)
for letters in 'pune':
print(letters)
person = {"name": "Joe", "age": 33, "city": "Paris"}
for key, value in person.items():
print(key, ":", value)
range function can be used for looping
for i in range(1,5,2):
print(i)
for j in range(5):
print(i)
if we provide just one element. start is assumed as zero and increment is by one.
use positional values are like this: (start, end, step)
Please note that start is included but end is not
while
and for
loopfor
loop is called as definite loop and while
loop can be called as indefinite loop because it simply loops untill specific condition is met..
continue
break
Breaks the loop.
pass
- A pass statement in Python is a placeholder statement which is used when the syntax requires a statement, but you don't want to execute any code or command.else
used with whileanimals = ('elephant', 'bear', 'bunny', 'dog', 'cat', 'velociraptor' )
for pet in animals:
if pet == 'bear':
continue
if pet == 'cat':
break
print(pet)
post by Pravin