Python Guess Game Fix
Python Guess Game Fix
Uploaded image
i am a beginner in python so i wanted to make this my first project but this is my code i have zero
experience i python where did i o wrong and show me and explain it to me in abeginner friendly
way:import random
Here’s a step-by-step, beginner-friendly way to both fix your logic and simplify your code:
python
But the loop only runs while `chances < guess`, so `chances > guess` can never be true inside the
loop.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/31
2. No `break` on correct guess
Even when `max_chances == computer_guess`, you never `break` out, so Python kept looping (or
would have tried to), which can cause confusing behavior.
3. Mixing “guess” and “chances”
Naming your variables so that one is called `guess` (but actually holds the max allowed tries) and
another `chances` (counting how many you’ve used) makes the logic hard to follow.
A cleaner rewrite
python
import random
# 1) Ask bounds
lower = int(input("Enter the lower bound: "))
upper = int(input("Enter the upper bound: "))
print(f"
break
🎉
# right answer!
Congratulations! You got it in {attempt} tries.")
else:
print(f" 😢
# this runs only if the loop never hit a `break`
Out of attempts! The number was {secret}.")
1. For-loop counting
python
— this neatly gives you both the current try number (`attempt`) and an “out of tries” handle in the
`else` block.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 2/31
`secret` is the computer’s hidden number.
Play around with that—once you feel comfy, you can extend it (e.g. let the user pick the number of
attempts, handle non-integer inputs with `try/except`, etc.). But this structure should eliminate the logic
bugs you were seeing and be much easier to follow.
python
Summary
This line creates a loop that runs exactly `max_attempts` times, giving you a counter
(`attempt`) that starts at 1 and ends at `max_attempts`. Under the hood, Python’s `range(start,
stop)` produces an iterable sequence of integers from `start` (inclusive) up to—but not
including—`stop`. By writing `max_attempts + 1` as the stop value, you ensure your loop
actually goes through `1, 2, ..., max_attempts`.
Iteration variable
Here, `attempt` is the loop variable. On each pass through the loop, Python assigns it the next value
from the iterable sequence Dataquest.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/31
Creates a sequence of integers
The built-in `range()` returns an object that generates numbers in order W3Schools.com
GeeksforGeeks.
Parameters
1. `start`: where to begin (inclusive).
2. `stop`: where to end (exclusive).
3. Optional `step`: how much to increment each time (defaults to `1`). Stack Overflow
Why “exclusive” stop?
Python’s convention of stopping before the `stop` value makes it easy to pair
`range(len(collection))` with zero-based indexing Python Wiki.
If you did `range(1, max_attempts)`, it would produce `1` through `max_attempts - 1` PYnative
.
3. Sequence produced:
1, 2, 3, …, max_attempts
4. When `attempt` finally equals `max_attempts`, the loop will run the last time—and then stop,
because the next “would-be” value equals `max_attempts+1`, which is excluded. Simplilearn.com
Built-in counting: You don’t need to manually increment and check a counter; Python handles it.
Readability: It’s clear “this runs N times,” and you already have the iteration number in `attempt`.
GeeksforGeeks
Further reading
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 4/31
Official docs on `for` loops: Python Wiki’s “ForLoop” Python Wiki
Sources
Summary
Yes—you can mirror the “N tries” behavior of a `for` loop using a `while` loop by manually tracking your
attempt count and breaking out when the guess is correct Python documentation. You initialize a
counter, loop while it’s within your allowed range, handle each guess inside the loop, then either `break`
on success or exit when you run out of attempts Stack Overflow.
1. Code Example
python
import random
max_attempts = 7
print(f"\nGuess a number between {lower} and {upper}. You have {max_attempts} tries.\n")
attempt = 1
while attempt <= max_attempts:
guess = int(input(f"Attempt {attempt}: Your guess? "))
print(f" 😢
# This else runs if the loop completes naturally (no break)
Out of attempts! The number was {secret}.")
2. How It Works
2.1 Initializing the Counter
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/31
We start by setting
python
attempt = 1
The line
python
ensures the body runs exactly `max_attempts` times—just like `for attempt in range(1,
max_attempts+1)` would Python Tutorials – Real Python.
2.4 Incrementing
python
attempt += 1
Python’s `while` supports an `else` block that runs only if the loop ends without a `break`
Python documentation.
We use that to print the “sorry, you’ve lost” message once all tries are used up
Python Tutorials – Real Python.
Flexibility: You can adjust the counter or exit conditions mid-loop if you later add features (like
“give a hint after 3 wrong tries”) Stack Overflow.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/31
Clarity for beginners: It reinforces the concept of loop conditions and counter updates explicitly
Python Tutorials – Real Python.
References
Python Tutorial: Control Flow Tools – While Loops (docs.python.org) Python documentation
GeeksforGeeks: Python While Loop Basics GeeksforGeeks
Real Python: Simplify While Loops Discussion Python Tutorials – Real Python
GeeksforGeeks: Loop Control in Python GeeksforGeeks
Real Python: Emulating Do-While Loops with `while` Python Tutorials – Real Python
Sources
Let’s walk through that loop step by step, so you can see exactly what’s happening and why:
python
attempt = 1
while attempt <= max_attempts:
guess = int(input(f"Attempt {attempt}: Your guess? "))
break
🎉
if guess == secret:
print(f" Correct! You found it in {attempt} tries.")
# ← jump out of the entire while‐loop immediately
elif guess < secret:
print("Too low! Try again.")
else:
print("Too high! Try again.")
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/31
1. Why start `attempt` at 1 (not 0)?
Human counting: We want “Attempt 1,” “Attempt 2,” … up through “Attempt 7.”
Loop condition: `while attempt <= max_attempts:` means “keep going as long as attempt is at
most 7.”
If we started at 0, you’d get “Attempt 0” on your first prompt, which looks odd for a user-facing
counter.
4. `break` immediately jumps you out of the entire `while`, so nothing else in the loop body runs—
including that `attempt += 1`.
That means if you got it on your 3rd try, `attempt` is still 3, and you correctly report “3 tries.”
On a wrong guess: you fall through past the `if`, hit `attempt += 1`, and go back around the loop
with the next attempt number.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/31
I hope that demystifies the flow! Let me know if any part still feels fuzzy.
attempt = 1
while attempt <= max_attempts:
guess = int(input(f"Attempt {attempt}: Your guess? "))
if guess == secret:
🎉
print(f" Correct! You found it in {attempt} tries.")
break # ← jump out of the entire while‐loop immediately
elif guess < secret:
print("Too low! Try again.")
else:
print("Too high! Try again.")
Summary
Your loop has a few key issues: the `break` is mis-indented causing a syntax/logical error, there’s no
handling if the user types something that isn’t an integer, and you never check that their guess falls
inside your chosen bounds or that the lower bound is actually less than the upper. Below, we’ll walk
through each bug in plain English and then present a complete, beginner-friendly rewrite that:
5. Clearly tells the user how many attempts they have and exactly what went wrong.
In your snippet the `break` sits outside the `if` block’s indentation, so Python either throws an
IndentationError or ignores it in the wrong place GeeksforGeeksStack Overflow.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 9/31
Calling `int(input(...))` will crash with a ValueError if the user types letters or punctuation
101 ComputingStack Overflow.
You don’t check that `lower < upper` before picking the secret number GeeksforGeeks.
You also don’t remind the user if they accidentally guess outside of that `[lower, upper]` range.
The loop might end without telling the user they’ve lost—unless they magically hit exactly the
wrong branch Medium.
import random
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 10/31
# 4) The guessing loop
attempt = 1
while attempt <= max_attempts:
# 4a) Ask for a guess, with input validation
try:
guess = int(input(f"Attempt {attempt}: Your guess? "))
except ValueError:
print(" ⇨ That’s not a whole number. Try again.\n")
continue # don’t count this as an attempt
print(f"
break
🎉
if guess == secret:
Correct! You found it in {attempt} tries.")
attempt += 1
Indentation Fixed: Every `break` now sits inside its `if` block, so Python runs it exactly when you
want GeeksforGeeks.
Robust Input: Using `try/except` around every `int(input())` means your program never crashes
on bad input Stack Overflow.
Range Checks: You ensure guesses stay within `[lower, upper]` so the player can’t wander off into
nonsense GeeksforGeeks.
Clear Loop Control: `while attempt <= max_attempts:` with an `else:` block cleanly handles “out of
tries” without extra flags Python documentation.
Friendly Messages: Every failure path tells the user exactly what went wrong and what to do next
Python Tutorials – Real Python.
Play with this version, and you’ll see your game feels much more polished—and your code won’t
mysteriously crash or miscount attempts!
Sources
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 11/31
print("⇨ Please type whole numbers only.\n")
continue
Here’s what that block does and why it’s written that way, broken down step by step:
A quick summary: this snippet uses an infinite loop (`while True`) to keep asking for two numbers until
the user types valid integer bounds; it wraps the input-and-conversion in a `try` block so any non-
integer entry raises a `ValueError` that’s caught by the `except`, which then prints a friendly message
and uses `continue` to start the loop over again without crashing your program Programiz
GeeksforGeeks.
python
while True:
means “repeat the indented block forever (or until you `break` out)” Programiz.
This is a common pattern when you want to keep prompting until the user gives you data you can
work with Stack Overflow.
try:
lower = int(input("Enter the LOWER bound (e.g. 1): "))
upper = int(input("Enter the UPPER bound (must be larger): "))
1. Python executes the code under `try:` normally, attempting to convert each input to an integer
GeeksforGeeksPython Tutorials – Real Python.
2. If both conversions succeed, no exception is raised and execution would move on (in your full code
you’d then validate the bounds and `break` out of the loop) Python Tutorials – Real Python.
except ValueError:
print("⇨ Please type whole numbers only.\n")
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 12/31
Catching bad input:
When `int(...)` fails because the user typed “five” or “3.14” or any non-integer text, Python raises
a `ValueError` Python Tutorials – Real Python.
The `except` block captures that specific exception so your program doesn’t crash – instead you
get a chance to tell the user “that wasn’t an integer, try again” GeeksforGeeks.
continue
This means you don’t accidentally run any code below (such as checking if `lower < upper`) unless
both inputs were valid integers.
This pattern ensures your program is robust (won’t die on bad input) and user-friendly (gives clear
guidance and keeps asking until it gets what it needs).
Sources
explain all this code line by line to zero levl experienced person in codin:import random
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 13/31
if lower >= upper:
print("⇨ Lower bound must be less than upper bound. Try again.\n")
else:
break
attempt += 1
Here’s a beginner‐friendly, line-by-line walkthrough of your complete guessing-game code. At the end
you’ll understand exactly what each part does and why it’s there.
Summary
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 14/31
This program lets the computer pick a secret number within bounds you choose, then gives you a fixed
number of attempts to guess it. It carefully checks that all inputs are valid integers, ensures your lower
bound is less than your upper, gives clear feedback on each guess (too high/low), and handles every
error case without crashing.
import random
What it does: Brings in Python’s built-in random library so you can later use `random.randint()` to
pick a secret number .
while True:
try:
lower = int(input("Enter the LOWER bound (e.g. 1): "))
upper = int(input("Enter the UPPER bound (must be larger): "))
except ValueError:
print("⇨ Please type whole numbers only.\n")
continue
1. `while True:`
Starts an infinite loop that will keep asking until you give two valid numbers .
2. `try:`
Begins a block where Python will attempt the indented code. If anything goes wrong with
integer conversion, it’ll jump to the `except` .
3. `lower = int(input(...))` and `upper = int(input(...))`
First calls `input()`, which pauses and waits for you to type text, then presses Enter .
Wraps that text in `int(...)`, converting it to a whole number—or raising `ValueError` if it
isn’t one .
4. `except ValueError:`
Catches any conversion errors (e.g. you typed “five” or “3.14”) so the program doesn’t crash .
5. `print("⇨ Please type whole numbers only.\n")`
Once you’ve entered two valid, ordered integers, `break` immediately exits the `while True`
loop so the program can move on .
Uses `random.randint(a, b)` to choose an inclusive random integer between your `lower` and
`upper` bounds .
max_attempts = 7
print(f"\nI’m thinking of a number between {lower} and {upper}.")
print(f"You have {max_attempts} attempts. Good luck!\n")
1. `max_attempts = 7`
Defines how many guesses the player gets.
attempt = 1
while attempt <= max_attempts:
# 4a) Ask for a guess, with input validation
try:
guess = int(input(f"Attempt {attempt}: Your guess? "))
except ValueError:
print(" ⇨ That’s not a whole number. Try again.\n")
continue # don’t count this as an attempt
print(f" 🎉
if guess == secret:
Correct! You found it in {attempt} tries.")
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 16/31
break
elif guess < secret:
print(" ➔ Too low! Try again.\n")
else:
print(" ➔ Too high! Try again.\n")
attempt += 1
`attempt = 1` sets your first guess number. Humans normally count from 1, not 0.
`if guess < lower or guess > upper:` checks you stayed within the bounds you set.
If out of range, it warns you and `continue`s (still not counting as an attempt).
Exact match: prints success and `break`s out of the loop immediately (so you don’t increment
`attempt` further).
5.6 Incrementing
`attempt += 1` runs only after a non-breaking iteration—so wrong guesses cost you exactly one try.
else:
print(f" 😢 Out of attempts! The number was {secret}.")
This `else` block on a `while` runs only if the loop ended without hitting a `break` .
It neatly covers the “you lost” case without extra flags.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 17/31
You’ve now seen every line explained in plain English. Feel free to tweak messages, change
`max_attempts`, or add more features (like a replay loop) now that you understand the core flow!
ok then what about this code of mine show me where i got wrong and how to do it better and give
me the correct code and explain it to a zero day python coder:import random
while True:
try:
lower = int(input("enter lower bound: "))
upper = int(input("enter upper bound: "))
except ValueError:
print("please put a whole number")
continue
if lower >= upper :
print("lower cannot be higher than upper")
else:
break
secret_number = random.randint(lower,upper)
attempt = 1
max_attempt = 7
print(f"am thinking of a number from {lower} - {upper}")
print(f"you have {max_attempt} max attempt")
if guess == secret_number:
print("congrats you won ")
break
elif guess < secret_number:
print("your guess was too low")
else:
print("your guess was too high")
attempt += 1
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 18/31
else:
print(f"bruh you lost after that many attempts the guess was {secret_number}")
Here’s a quick overview of what’s happening—and how we can make it clearer, more robust, and easier
for a brand-new Python coder to follow:
What’s going wrong: your logic mostly works, but there are small bugs (mis-counted attempts,
unclear messages) and missing checks (no feedback when they win on the last try, variable naming
could be clearer).
How to improve: use consistent names, validate inputs more cleanly, and structure the loop so
every case (win, lose, invalid input) is handled gracefully.
The corrected code below is fully annotated for a “zero-day” Python learner, then we’ll walk
through each section line by line in plain English.
import random
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 19/31
break # valid bounds, exit this input loop
print(f" 🎉
if guess == secret:
Congratulations—you got it in {attempt} tries!")
break # exit the loop immediately on win
elif guess < secret:
print(" ➔ Too low! Try again.\n")
else:
print(" ➔ Too high! Try again.\n")
# 5) --- If we never hit `break`, the player ran out of attempts ---
else:
print(f" 😢Out of attempts! The number was {secret}.")
Loads Python’s random toolbox so we can have the computer pick a number for us.
2. `while True:`
Starts a loop that will run until we explicitly `break` out. We use this to keep asking for valid
bounds.
3. `try: ... except ValueError:`
We attempt to turn whatever the user types into an integer (`int(...)`).
If they type letters or decimals, Python raises a “ValueError” and jumps into the `except`
block, where we print an error and `continue` back to the top of the loop.
4. `if lower >= upper:`
Ensures the first number (`lower`) really is smaller than the second (`upper`). If not, we warn
them and loop again.
5. `break`
Exits the `while True` loop once we have two valid, ordered integers.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 20/31
6. `secret = random.randint(lower, upper)`
The computer quietly picks a random whole number between `lower` and `upper`, inclusive.
If they guess outside the bounds, we print a reminder and `continue`—again, not costing an
attempt.
11. Comparing answer
If the guess matches `secret`, we congratulate and `break` out of the loop.
Otherwise, we give a “too low” or “too high” hint and (after that) increment `attempt` by 1.
12. `else:` on the `while`
In Python, a `while` can have an `else` that only runs if the loop ended naturally (i.e., never
hit a `break`). Here it prints the “you lost” message and reveals the secret.
With these changes and this explanation, your game will be reliable, clear, and friendly—even for
someone who’s never written a line of code before. Give it a try and watch how each part works!
Uploaded image
modify the code to this :Most of the geeks from a CS (Computer Science) background, think of their
very first project after doing a Programming Language. Here, you will get your very first project and
the basic one, in this article.
Explanation 1: If the User inputs range, let’s say from 1 to 100. And compiler randomly selected
42 as the integer. And now the guessing game started, so the user entered 50 as his/her first guess.
The compiler shows “Try Again! You guessed too high”. That’s mean the random number (i.e., 42)
doesn’t fall in the range from 50 to 100. That’s the importance of guessing half of the range. And
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 21/31
again, the user guesses half of 50 (Could you tell me why?). So the half of 50 is 25. The user enters
25 as his/her second guess. This time compiler will show, “Try Again! You guessed too small”. That’s
mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user
guessing is shorter, i.e., from 25 to 50. Intelligently! The user guessed half of this range, so that,
user guessed 37 as his/her third guess. This time again the compiler shows the output, “Try Again!
You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the
guessing range for user is from 37 to 50, for which the user guessed 43 as his/her fourth guess. This
time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing
range for users will be from 37 to 43, again for which the user guessed the half of this range, that is,
40 as his/her fifth guess. This time the compiler shows the output, “Try Again! You guessed too
small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as
his/her sixth guess. Which is wrong and shows output “Try Again! You guessed too small”. And
finally, the User Guessed the right number which is 42 as his/her seventh guess.
Explanation 2: If the User inputs range, let’s say from 1 to 50. And compiler randomly selected 42
as the integer. And now the guessing game started. So the half of 50 is 25. The user enters 25 as
his/her First guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the
integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is
shorter, i.e., from 25 to 50. Intelligently! User guessed half of this range, so that, user guessed 37 as
his/her second guess. This time again the compiler shows the output, “Try Again! You guessed too
small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range
for user is from 37 to 50, for which the user guessed 43 as his/her third guess. This time the
compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for
users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as
his/her fourth guess. This time the compiler shows the output, “Try Again! You guessed too small”.
Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her
fifth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the
User Guessed the right number which is 42 as his/her sixth guess.
So, the minimum number of guesses depends upon range. And the compiler must calculate the
minimum number of guessing depends upon the range, on its own. For this, we have a formula:-
Step-by-step algorithm:
User inputs the lower bound and upper bound of the range.
The compiler generates a random integer between the range and store it in a variable for future
references.
For repetitive guessing, a while loop will be initialized.
If the user guessed a number which is greater than a randomly selected number, the user gets an
output “Try Again! You guessed too high“
Else If the user guessed a number which is smaller than a randomly selected number, the user gets
an output “Try Again! You guessed too small”
And if the user guessed in a minimum number of guesses, the user gets a “Congratulations! ”
Output.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 22/31
Else if the user didn’t guess the integer in the minimum number of guesses, he/she will get “Better
Luck Next Time!” output.
Below is the Implementation of the Algorithm:
import random
print("Hi welcome to the game, This is a number guessing game.\nYou got 7 chances to guess the
number. Let's start the game")
number_to_guess = random.randrange(100)
chances = 7
guess_counter = 0
guess_counter += 1
my_guess = int(input('Please Enter your Guess : '))
if my_guess == number_to_guess:
print(f'The number is {number_to_guess} and you found it right !! in the {guess_counter}
attempt')
break
Time Complexity:
The time complexity of this code is O(log2n) where n is the difference between lower and upper
bound of the range.
Space Complexity:
The space complexity of this code is O(1) as all the variables used in this code are of the same size
and no extra space is required to store the values.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 23/31
Below is a complete, beginner-friendly rewrite of your “minimum-guesses” version of the game. It:
1. Asks you for a lower and upper bound (validates they’re integers and ordered).
2. Picks a secret number in that range.
3. Computes the minimum number of guesses needed by the formula
python
python
import random
import math
if guess == secret:
# 5a) If we guessed exactly on or before the last allowed try
print(f"
else:
🎉
if attempt == min_guesses:
Congratulations! You found it in {attempt} guesses—the minimum possible!")
👍
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 24/31
print(f" 👍
You got it in {attempt} guesses—but the theoretical minimum was {min_guesses}
print("Better luck next time!")
break
attempt += 1
python
while True:
try:
lower = int(input("Enter the LOWER bound…"))
upper = int(input("Enter the UPPER bound…"))
except ValueError:
print("Please type whole numbers only.")
continue
if lower >= upper:
print("Lower bound must be less than upper bound.")
else:
break
Inside, we `input()` two values and try to turn them into integers.
If you type something invalid, `int(...)` raises `ValueError`, we catch it, show an error, and
`continue` back to the top.
Once we have two integers, we check that the first is less than the second; only then do we
`break` out.
python
Chooses one whole number between your `lower` and `upper`, inclusive.
4. Compute minimum guesses
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 25/31
python
python
6. Guessing loop
python
attempt = 1
while attempt <= min_guesses:
…
if guess == secret:
…
break
…
attempt += 1
else:
print("Out of guesses! …")
7. On a correct guess
python
print(" 🎉
if attempt == min_guesses:
Congratulations! … minimum possible!")
else:
print(" 👍 You got it … Better luck next time!")
A game that automatically computes how many guesses you should need,
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 26/31
Robust input checks so it never crashes, and
Clear, beginner-friendly prompts and comments explaining each step.
Happy coding!
Most of the geeks from a CS (Computer Science) background, think of their very first project after
doing a Programming Language. Here, you will get your very first project and the basic one, in this
article.
Explanation 1: If the User inputs range, let’s say from 1 to 100. And compiler randomly selected
42 as the integer. And now the guessing game started, so the user entered 50 as his/her first guess.
The compiler shows “Try Again! You guessed too high”. That’s mean the random number (i.e., 42)
doesn’t fall in the range from 50 to 100. That’s the importance of guessing half of the range. And
again, the user guesses half of 50 (Could you tell me why?). So the half of 50 is 25. The user enters
25 as his/her second guess. This time compiler will show, “Try Again! You guessed too small”. That’s
mean the integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user
guessing is shorter, i.e., from 25 to 50. Intelligently! The user guessed half of this range, so that,
user guessed 37 as his/her third guess. This time again the compiler shows the output, “Try Again!
You guessed too small”. For the user, the guessing range is getting smaller by each guess. Now, the
guessing range for user is from 37 to 50, for which the user guessed 43 as his/her fourth guess. This
time the compiler will show an output “Try Again! You guessed too high”. So, the new guessing
range for users will be from 37 to 43, again for which the user guessed the half of this range, that is,
40 as his/her fifth guess. This time the compiler shows the output, “Try Again! You guessed too
small”. Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as
his/her sixth guess. Which is wrong and shows output “Try Again! You guessed too small”. And
finally, the User Guessed the right number which is 42 as his/her seventh guess.
Explanation 2: If the User inputs range, let’s say from 1 to 50. And compiler randomly selected 42
as the integer. And now the guessing game started. So the half of 50 is 25. The user enters 25 as
his/her First guess. This time compiler will show, “Try Again! You guessed too small”. That’s mean the
integers less than 25 (from 1 to 25) are useless to be guessed. Now the range for user guessing is
shorter, i.e., from 25 to 50. Intelligently! User guessed half of this range, so that, user guessed 37 as
his/her second guess. This time again the compiler shows the output, “Try Again! You guessed too
small”. For the user, the guessing range is getting smaller by each guess. Now, the guessing range
for user is from 37 to 50, for which the user guessed 43 as his/her third guess. This time the
compiler will show an output “Try Again! You guessed too high”. So, the new guessing range for
users will be from 37 to 43, again for which the user guessed the half of this range, that is, 40 as
his/her fourth guess. This time the compiler shows the output, “Try Again! You guessed too small”.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 27/31
Leaving the guess even smaller such that from 41 to 43. And now the user guessed 41 as his/her
fifth guess. Which is wrong and shows output “Try Again! You guessed too small”. And finally, the
User Guessed the right number which is 42 as his/her sixth guess.
So, the minimum number of guesses depends upon range. And the compiler must calculate the
minimum number of guessing depends upon the range, on its own. For this, we have a formula:-
Step-by-step algorithm:
User inputs the lower bound and upper bound of the range.
The compiler generates a random integer between the range and store it in a variable for future
references.
For repetitive guessing, a while loop will be initialized.
If the user guessed a number which is greater than a randomly selected number, the user gets an
output “Try Again! You guessed too high“
Else If the user guessed a number which is smaller than a randomly selected number, the user gets
an output “Try Again! You guessed too small”
And if the user guessed in a minimum number of guesses, the user gets a “Congratulations! ”
Output.
Else if the user didn’t guess the integer in the minimum number of guesses, he/she will get “Better
Luck Next Time!” output.
Below is the Implementation of the Algorithm:
import random
print("Hi welcome to the game, This is a number guessing game.\nYou got 7 chances to guess the
number. Let's start the game")
number_to_guess = random.randrange(100)
chances = 7
guess_counter = 0
guess_counter += 1
my_guess = int(input('Please Enter your Guess : '))
if my_guess == number_to_guess:
print(f'The number is {number_to_guess} and you found it right !! in the {guess_counter}
attempt')
break
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 28/31
elif guess_counter >= chances and my_guess != number_to_guess:
print(f'Oops sorry, The number is {number_to_guess} better luck next time')
Time Complexity:
The time complexity of this code is O(log2n) where n is the difference between lower and upper
bound of the range.
Space Complexity:
The space complexity of this code is O(1) as all the variables used in this code are of the same size
and no extra space is required to store the values.
1. Asks for and validates lower and upper bounds, repeating until you enter two integers with the
lower less than the upper. Stack Overflow
2. Picks a secret number in that range using `random.randint`. Python documentation
3. Calculates the theoretical minimum number of guesses as
python
5. On a correct guess within the allowed tries, it tells you if you hit the theoretical minimum or not.
Otherwise it prints “Better luck next time!” or the final “out of guesses” message via the `while …
else` construct. Python documentation
Code Implementation
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 29/31
python
import random
import math
print(f"\nI’m thinking of a number between {lower} and {upper}.") # f-string for clarity :contentRe
print(f"You have {min_guesses} guesses to find it (in theory).\n")
print(f" 🎉
if attempt == min_guesses:
Congratulations! You found it in exactly {attempt} guesses—the minimum possib
else:
print(f" 👍 You got it in {attempt} guesses, although you needed only {min_guesses}. Bett
break # exit on success
elif guess < secret:
print(" ➔ Too low! Try again.\n")
else:
print(" ➔ Too high! Try again.\n")
How It Works
1. Validating the Range
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 30/31
We use a `while True:` infinite loop and wrap the two `input()` calls in a `try/except ValueError`
so that typing anything other than a whole number doesn’t crash the program. Stack Overflow
After converting both to `int`, we check that `lower < upper`; otherwise we prompt again and
loop. Stack Overflow
`random.randint(lower, upper)` picks one integer uniformly between your bounds, inclusive.
Python documentation
Binary search shows you can halve the interval each time, so in the worst case you need
We loop `while attempt <= min_guesses:` so you get exactly that many tries. If you ever `break` (by
guessing correctly), Python skips the `else:` block at the end. Python documentation
Each iteration:
1. We again `try/except` around `int(input(...))` so invalid entries don’t count as an
attempt. GeeksforGeeks
2. We check the guess is within `[lower, upper]`, otherwise we prompt again without
incrementing. Stack Overflow
3. We compare `guess` to `secret`, printing “too low” or “too high” hints.
4. If it’s exactly right, we check whether `attempt == min_guesses` to decide between a true
“minimum-possible” win message or a “you were lucky but not optimal” message, then
`break`.
5. Out of Guesses
If the loop condition ever becomes false without hitting the `break`, Python runs the `else:` block
and prints your final “better luck next time” message. Python documentation
This structure makes your game robust (no crashes), optimal (computes its own minimum tries), and
clear (friendly messages at every step). Enjoy experimenting!
Sources
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 31/31