Replace while with for¶
Sourcery refactoring id: while-to-for¶
Description:¶
Replaces a while loop with a counter by a for loop
Before:¶
i = 0
while i < 10:
print("I love hats")
i += 1
After:¶
for i in range(10):
print("I love hats")
Explanation:¶
We often need to iterate over the same bit of code a certain number of times.
Developers who are unfamiliar with Python may consider using a while loop for
this, but it's almost certainly better to use for.
Converting from while to for means the explicit handling of the counter can
be removed, shortening the code and making it esier to read.