Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Using break to Process User Input

Resource mentioned in this lesson: Python while Loops: Repeating Tasks Conditionally

00:00 Open up your IDE of choice because in this lesson you’ll be writing a number guessing game making use of break and a while loop.

00:07 This game will generate a random integer from one to 10, and the user will have four guesses to get it right, otherwise they lose. You’ll need the random module.

00:14 So start with that: import random. Now define the main function called guess_the_number(). def guess_the_number(): Create a variable for tracking the number of guesses remaining, set to four: guesses_left = 4 and generate a random number using the randint() function from the random module.

00:34 random_number = random.randint(1 , 10), the inclusive range of potential return values. And now you’re ready to enter the while loop.

00:44 This loop is meant to repeat until a break statement runs, so you can use True as its condition: while True: and now the core game logic.

00:53 First, check if the user is out of guesses. if guesses_left <= 0: print() "You ran out of guesses".

01:06 "The correct number was {random_number}". And since they ran out of guesses, use a break statement to exit the game loop. By the way, these strings on two separate lines will be combined by Python into a single string at runtime.

01:20 And this is known as string literal concatenation. It’s a nice way to keep the line length down without using escape characters. Next, if the user hasn’t run out of guesses, they need to make a guess or quit the game.

01:31 Use the built-in input() function for this. It shows the user a message prompting them to provide an input, which is then returned from the function as a string.

01:39 guess = input("Guess the number between one and 10".

01:44 Enter q to quit.") If guess == "q":

01:52 print() "Successfully exited the game" and break.

01:59 So if guess is not equal to “q”, you need to check if guess is a valid number and if not, inform the user. elif not is the result of calling guess .isnumeric(): print() "Please enter a valid value."

02:15 No break here because the game isn’t over yet. Then, because guess is a string, convert it to an int and compare it with the random_number.

02:22 If it matches, inform the user that they won and then break. elif int(guess) function is equal == random_number: print() "Congratulations! You picked the correct number" and break.

02:39 And now if none of those elif conditions are true, the user has submitted a valid number that’s incorrect. So let them know and reduce the number of guesses remaining by one, informing them of their attempts remaining. else: print() “Sorry, your guess was incorrect.”

02:57 guesses_left -= 1

03:01 and print the f-string: print(f"You have {guesses_left} guesses left.")

03:09 Then use the if __name__ == "__main__": guard to ensure that the game only runs when executed directly. if __name__ == "__main__": run guess_the_number().

03:24 All that’s left to do is save the file, open the integrated terminal, and play a few rounds: python guess_the_number.py. Looks good so far.

03:34 Guess the number between one and 10. Enter q to quit. Let’s see if I can hit each of the conditions. Try an invalid number, 5. Please enter a valid value.

03:44 Okay, 5. Sorry, your guess was incorrect. Three guesses left. Try 4. Incorrect again. Try 3. Try 2. And ran out of guesses. The correct number was 1.

04:00 So losing the game works. Let’s see if we can win this time. Guess 5, guess 4, guess 3, guess 2. Alright, 2 was the correct number and the game ended properly.

04:13 That was a pretty fun little game and a great example of using multiple breaks within a while loop. To dive even deeper with while loops, I recommend “Python while Loops: Repeating Tasks Conditionally”.

04:25 As for us, one layer of loops isn’t always enough. No, we need to go deeper. See more in the next lesson.

Become a Member to join the conversation.