Use Loops to Avoid Repetitive Code
00:00 Use Loops to Avoid Repetitive Code. When playing Wordle, you get up to six chances to guess the correct word. One way to achieve the same in your game would be to copy the code that you’ve already written and repeat it six times, but that’s a bad idea for several reasons. Most importantly, it would be inefficient and complicated to maintain. Instead, you’ll use loops to achieve the repeating behavior.
Python supports two main looping constructs:
while. Typically, you’ll use
for when doing definite iteration—you know in advance how many times you want to loop. On the other hand,
while is great for indefinite iteration, where you don’t know up front how many times you need to repeat an action.
00:45 There are other ways to create loops. Some programming languages rely on recursive function calls to create loops, and later in this course, you’ll see an example of using a recursive loop in Python, as well. In general, though, you shouldn’t use recursion for looping in Python. Function calls are quite slow, and there are no optimizations for recursion, as you may find in other languages.
Become a Member to join the conversation.