Python Loops And Statements


while loop
when condition of given statements is True, while loop is execute.
Example:
i = 0
while i < 5:
  print(i)
  i += 1
Output:
0
1
2
3
4
Break and Continue Statements
*In Python, break and continue statements can alter the flow of a normal loop.
*Loops iterate over a block of code until test expression is false, but sometimes we wish to terminate the current iteration or even the whole loop without checking test expression.
*The break and continue statements are used in these cases.
While loop with break Statements:
Example:
i = 0
while i < 5:
  print(i)
  if i == 3:         #break the loop
    break
  i +=1
Output: 
0
1
2
3
While loop with continue Statements:
Example:
i = 0
while i < 5:
  i += 1
  if i == 3:     #continue the loop
    continue
  print(i)
Output:
1
2
4
5
For Loop
for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example:
Alphabets = ["a", "b", "c"]
for x in Alphabets:
  print(x)
Output:
a
b
c

for loop with break Statements
Example:
Alphabets = ["a", "b", "c"]
for x in Alphabets:
  if x == "b":
      break
  print(x)
Output:
a
for loop with continue Statements
Example:
Alphabets = ["a", "b", "c"]
for x in Alphabets:
  if x == "a":
      continue
  print(x)
Output:
b
c

Comments

Popular posts from this blog

Basic Operators in Python

Python Conditions