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.
00:26
Python supports two main looping constructs: for
and 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.
01:09
Usually you’ll be better off sticking to regular loops. Here, you want to ask the user six times to guess the word, so you’ll use a for
loop.
01:22
By looping over a range
, you’ll also count the number of guesses and display that number to the user.
01:35
There’s no point in letting the user keep guessing once they’ve found the correct answer. So you use a break
statement to break out of the loop early if the user guesses the right word.
01:45
An additional bonus of introducing break
is that you don’t need the explicit else
anymore. Your code only continues if the guess is wrong.
01:55 You can see the latest version of the code in action on-screen.
02:04 Next, it’s time to make the game more playable by adding some proper feedback. In the next section of the course, you’ll see how you can enumerate which letters the user has guessed correctly.
Become a Member to join the conversation.