Python Programming - Guessing Game
Program Objective
The objective of this program is to generate a random number between 1 and 20 and prompt the user to guess the number until they get it right. The initial program run will look like this:
Flowchart in Sentence Format
- Generate a random number between 1 and 20.
- Prompt the user to guess the number.
- If the guess is correct, print a congratulatory message and exit the program.
- If the guess is incorrect, provide feedback to the user (too high or too low) and prompt them to guess again.
- Repeat steps 2-4 until the user guesses the correct number.
Pseudocode
Source Code
Line-by-Line Description
import random
This line imports the random module, which is used to generate a random number.
number = random.randint(1, 20)
This line generates a random integer between 1 and 20 and assigns it to the variable number.
num_guesses = 0
This line initializes the variable num_guesses to 0, which will be used to keep track of the number of guesses the user makes.
while True:
This line starts a while loop that will repeat indefinitely until the user guesses the correct number and the break statement is executed.
guess = int(input("Guess the number between 1 and 20: "))
This line prompts the user to guess the number and assigns their guess to the variable named guess. The int() function is used to convert the user's input from a string to an integer.
num_guesses += 1
This line increments the variable num_guesses by 1 for each guess the user makes.
if guess == number:
This line checks whether the user's guess is equal to the random number generated by the program.
print("Congratulations! You guessed the number in", num_guesses,
"guesses.")
This line prints a congratulatory message to the user and the number of guesses they made if they guessed the correct number.
break
This line exits the while loop and ends the program.
elif guess < number:
This line checks whether the user's guess is less than the random number generated by the program.
print("Too low. Guess again.")
This line provides feedback to the user that their guess was too low.
else:
This line executes if the user's guess is not equal to the random number generated by the program and it is not less than the random number.
print("Too high. Guess again.")
This line provides feedback to the user that their guess was too high.
print()
This line adds a blank line for spacing.
The while loop continues from step 4 until the user guesses the correct number. Then, program ends.
Sample Program Run
In this example, the user guessed 10 on their first try, which was too low. They guessed 15 on their second try, which was too high. Finally, they guessed 13 on their third try, which was correct. The program then printed a congratulatory message telling the user how many guesses it took them to get the correct answer.
Flashcards
Here are interactive flashcards to reinforce ideas from this blog post.
Image by Gerd Altmann from Pixabay
Comments
Post a Comment