Greetings, and welcome back to our Python tutorial series on CipherTrick.com! In this tutorial, we’re going to take a close look at ‘while’ loops in Python. ‘While’ loops are a fundamental control flow mechanism that allow for repeated execution of a block of code as long as a certain condition is met.
Part 1: The Basics of ‘While’ Loops
In Python, a ‘while’ loop repeatedly executes a target statement as long as a given condition is true. Here’s the basic syntax:
while condition: # execute these statements
Here’s an example:
count = 0 while count < 5: print(count) count += 1 # increment count
This code prints numbers from 0 to 4, each on a new line. The loop continues until
count is no longer less than 5.
Part 2: The ‘break’ and ‘continue’ Statements
Just like with ‘for’ loops, ‘while’ loops can utilize the ‘break’ and ‘continue’ statements to modify the loop’s control flow.
break statement allows for an early exit from the loop:
count = 0 while count < 10: if count == 5: break print(count) count += 1
In this code, the loop is terminated as soon as
count equals 5, so only numbers from 0 to 4 are printed.
continue statement skips the rest of the current loop iteration and immediately starts the next one:
count = 0 while count < 10: count += 1 if count == 5: continue print(count)
In this code, the number 5 is not printed because the
continue statement skips the
print(count) statement when
count equals 5.
Part 3: The ‘else’ Clause in ‘While’ Loops
Python’s ‘while’ loops also support an ‘else’ clause which most other programming languages do not offer. The
else block executes after the loop finishes execution, but only if the loop ends normally (i.e., it is not exited by a ‘break’ statement).
count = 0 while count < 5: print(count) count += 1 else: print("Loop has ended")
This code will print numbers from 0 to 4 and then print “Loop has ended”.
‘While’ loops are a versatile tool in Python, allowing for repeated execution of a block of code based on a condition. Understanding ‘while’ loops, along with their control statements, is key to writing efficient and effective Python code. Keep practicing, and in our next tutorial, we’ll move onto more advanced Python topics. Until then, happy coding!