While loop

What is While loop in Python?
  • A While loop in Python is used to execute a set of statements/ iterate over a block of code repeatedly as long as the given condition is true.
  • While loop is preferred when we don't know the number of iterations.
Syntax:
                    while condition:
                            body statements
  • The body statement of the while loop is separated from the rest of the code using indentation [tab].
Flow/Working of While loop:
  • In the While loop, the Given condition is checked first. If the condition is true then only the loop starts to execute the body statements.
  • After one iteration, the condition is checked again and the process continues until the condition evaluates to False.
  • Python interprets any non-zero value as TRUE. None and 0 are interpreted as False.
While loop - Example
Output
While loop with Else:
  • Just like for loop, While loop can also have an optional 'else' block.
  • The 'else' block will be executed only when the given condition becomes false.
  • Else block won't be executed for cases like break out of the loop (terminated by break statement) or if an exception is raised.
While loop - else block
Output
Nested While loop:
  • A While loop inside another while loop is called nested while loop.
  • See the below example to understand this concept.
Nested While Loop
Output

No comments:

Post a comment