Skip to content

script_16.py - Number Guessing Game

Code

Python
#!/usr/bin/env python3
"""Number guessing game"""

import random

target = random.randint(1, 100)
attempts = 0

while True:
    guess = int(input("Guess a number (1-100): "))
    attempts += 1

    if guess < target:
        print("Too low!")
    elif guess > target:
        print("Too high!")
    else:
        print(f"Correct! You guessed it in {attempts} attempts.")
        break

Explanation

Line 4: import random - Imports random module for random number generation

Line 6: target = random.randint(1, 100) - .randint() is method from random module - Returns random integer between arguments (inclusive) - Range is 1 to 100 (both endpoints included) - target is integer type, the number to guess - Generated once before loop

Line 7: attempts = 0 - Counter for number of guesses (integer type)

Line 9: while True: - True is a boolean literal (always True) - Creates infinite loop (condition never becomes False) - Loop runs forever unless manually exited - Must use break to exit

Line 10: guess = int(input("Guess a number (1-100): ")) - Gets user input inside loop - Converted to integer for comparison

Line 11: attempts += 1 - Increments counter each iteration - Tracks total guesses made

Line 13-16: Conditional logic - Provides feedback based on comparison

Line 19: break - Exits the while loop immediately - Only executes when guess == target (else block) - Without this, loop would be truly infinite