Replace while with for
Documentation Index
Fetch the complete documentation index at: https://docs.sourcery.ai/llms.txt
Use this file to discover all available pages before exploring further.
Sourcery refactoring id: while-to-for
Section titled “Sourcery refactoring id: while-to-for”Description:
Section titled “Description:”Replaces a while loop with a counter by a for loop
Before:
Section titled “Before:”i = 0while i < 10: print("I love hats") i += 1After:
Section titled “After:”for i in range(10): print("I love hats")Explanation:
Section titled “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.