Number Guessing Game
Start with Number Guessing Game
Learn number guessing game through an executable example, then connect the small demonstration to production code.
What you’ll learn
- Explain the main purpose of number guessing game.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
A guessing game practices loops, comparisons and state. A fixed secret and scripted guesses make the first version deterministic; interactive input can be added once the logic is correct.
For a fair game, limit attempts and validate input. Production or multiplayer randomness should use an appropriate randomness source for the required threat model.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Tools, syntax and practical notes
Interactive version: use bufio.NewScanner(os.Stdin), strconv.Atoi and a finite attempt loop. Generate a secret with a suitable RNG and clearly define the range and win conditions.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
secret := 7
guesses := []int{3, 9, 7}
for attempt, guess := range guesses {
fmt.Printf("Attempt %d: ", attempt+1)
switch {
case guess < secret:
fmt.Println("Too low")
case guess > secret:
fmt.Println("Too high")
default:
fmt.Println("Correct!")
return
}
}
fmt.Println("No more attempts")
}
Output
Attempt 1: Too low
Attempt 2: Too high
Attempt 3: Correct!Trace what the program does
The first guess is below seven, the second exceeds seven, and the third equals seven. The function returns immediately after the correct guess.
Avoid common mistakes
- Separate the hidden secret from displayed feedback.
- Validate user input and do not let failed parsing consume unlimited memory or attempts.
Try it yourself
Replace scripted guesses with a scanner, add a maximum of five attempts, and test invalid entries.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Number Guessing Game in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.