Random Number
Python Coding Problems
Conditional Statements
Loops & Iterations
Data Lists & Collections
Area Calculator
Grade Calculator
Make a Username
Voting Age
Multiplication Table
Factorial
Say Hello
Palindrome
Random Number
To-Do List
Random Number
Topic: Random Number Guessing Game
Description: The program generates a secret random number between 1 and 50. It then enters a conditional control loop where it continually accepts user guesses, letting them know if their answer is too high, too low, or correct.
Why: This game exposes students to importing core utility standard libraries (random), maintaining structural loop counter indices, and managing indefinite iteration constraints using structural break keywords.
Program Code
import random def start_guessing_game(): print("=============================") print(" RANDOM GUESSING MATRIX ") print("=============================") print("I have selected a hidden number between 1 and 50.") secret_number = random.randint(1, 50) attempts = 0 while True: try: guess = int(input("\nTake a guess: ").strip()) except ValueError: print("Invalid Input. Please enter a valid whole number integer.") continue attempts += 1 if guess < secret_number: print("📉 Too low! Try a higher value.") elif guess > secret_number: print("📈 Too high! Try a lower value.") else: print("\n🎉 CONGRATULATIONS!") print(f"You decoded the number {secret_number} in exactly {attempts} attempts!") break # Launch game routine start_guessing_game()
Expected Console Output Examples
============================= RANDOM GUESSING MATRIX ============================= I have selected a hidden number between 1 and 50. Take a guess: 25 📉 Too low! Try a higher value. Take a guess: 38 📈 Too high! Try a lower value. Take a guess: 32 🎉 CONGRATULATIONS! You decoded the number 32 in exactly 3 attempts! -----------------------------
Core Syntax & Concept Breakdown
- Indefinite Loops (
while True): Sets up a loop structure that will theoretically repeat infinitely unless explicitly instructed to terminate using internal system overrides. - Loop Control Modifiers (
continuevsbreak): Thecontinuestatement skips any remaining lines inside the current loop sequence to restart immediately at the top block, whereasbreakimmediately cuts operations and exits the structural framework loop entirely.
🏋️ Test Yourself With Exercises
Take our quiz on Random Number to test your knowledge.
Browse Quizzes »