Python While লোপ

Python loop

Python has two primitive loop commands:

  • while Loop
  • for Loop

while loop

If used while Loop, we can execute a group of statements as long as the condition is true.

Instance

Print i as long as i is less than 7:

i = 1
while i < 7:
  print(i)
  i += 1

ইনস্ট্যান্স চালু করুন

Note:Remember to increment iotherwise the loop will continue forever.

while The loop needs to prepare the relevant variables. In this instance, we need to define an index variable iwe set it to 1.

break statement

If used break Statement, even if the while condition is true, we can stop the loop:

Instance

Exit the loop when i equals 3:

i = 1
while i < 7:
  print(i)
  if i == 3:
    break
  i += 1

ইনস্ট্যান্স চালু করুন

continue statement

If used continue Statement, we can stop the current iteration and continue to the next:

Instance

If i equals 3, continue to the next iteration:

i = 0
while i < 7:
  i += 1 
  if i == 3:
    continue
  print(i)

ইনস্ট্যান্স চালু করুন

else statement

By using the else statement, we can run a code block when the condition no longer holds:

Instance

When the condition is false, print a message:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

ইনস্ট্যান্স চালু করুন