Python Forum
Guessing game with comparison operators
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Guessing game with comparison operators
#1
I’m working with a Udemy course.

Here is the challenge:

Quote:Let's use while loops to create a guessing game.
The Challenge:
Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:
  1. If a player's guess is less than 1 or greater than 100, say "OUT OF BOUNDS"
  2. On a player's first turn, if their guess is
    • within 10 of the number, return "WARM!"
    • further than 10 away from the number, return "COLD!"
  3. On all subsequent turns, if a guess is
    • closer to the number than the previous guess return "WARMER!"
    • farther from the number than the previous guess, return "COLDER!"
  4. When the player's guess equals the number, tell them they've guessed correctly and how many guesses it took!

You can try this from scratch, or follow the steps outlined below. A separate Solution notebook has been provided. Good luck!

Here is my attempt:

import random
print("Here are the rules: \n'Guess a number between 1 and 100.' \n'We'll give you a hint if you need one.'")
num = int(random.randint(1,100))
print(num)
guess_count = int(1)
guess = int(input("Guess a number! "))
orbit_greater = num + 10
orbit_less = num - 10
while guess != num:
    guess_count = guess_count + 1    
    if guess > num < orbit_greater:
        print("WARM")
    if guess < num > orbit_less:
        print("WARM")    
    if guess <= 0:
        print("Out of Bounds. Try again.")
    if guess > 100:
        print("Out of Bounds. Try again.")
    guess = int(input("Guess again: "))
if guess == num:
    print("You've won! It took you %d tries, but you got it. " % (guess_count))
It (sort of) runs. I can only tick off half the number of features. What my script already accomplishes is prompt the user when s/he is out of bounds. And if the user guesses correctly, it will print the total number of guesses entered (attempts made). What my script doesn’t yet properly do is assess if the guess is within 10 integers of the number in either direction (higher or lower).

When I run the script and enter a number, it will always say “WARM” regardless of how close it is, whether it is within a 10 integer orbit or not. The problem lines are clearly 11-14.

I understand the basics of comparison operators but I struggle to implement them (lines 11-14) in this particular advanced exercise.

edit: It's also worth mentioning that I have tried many, many different combinations of > and < at lines 11 and 13 which I still can't find the right adjustment.

Can anyone here provide some guidance?

The Udemy course material can be found on the instructor’s official GitHub repo at Complete-Python-3-Bootcamp/01-Python Comparison Operators/01-Comparison Operators.ipynb
Reply
#2
Note that if the guess is within 10, then abs(guess - num) <= 10 is True.

To tell if it's warmer or colder, you will want to keep track of the previous guess. Typically you would just store the current guess as the previous guess at the end of the loop. Since there is different behavior on the first guess, you could code that behavior before the loop, and then store the first guess as the previous guess between that and starting the loop.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
(Nov-30-2018, 03:23 PM)ichabod801 Wrote: Note that if the guess is within 10, then abs(guess - num) <= 10 is True.

Thanks, @ichabod801. This really helps. Now that I see this code, I see how it works. In this expression, the user’s guess is subtracted by num which is cast using an absolute value conversion (a built in function). If this absolute integer is less than or equal to 10, this means it is within the orbit of 10 integers in either direction. This is brilliant and magical. It makes sense to me now. But coming up with this combination or arguments and operations independently on my own is not obvious. Perhaps it’s necessary that I refresh on basic high-school math before learning any more Python? This operation should come naturally, especially given that this exercise is for beginners.

Quote:To tell if it's warmer or colder, you will want to keep track of the previous guess. Typically you would just store the current guess as the previous guess at the end of the loop. Since there is different behavior on the first guess, you could code that behavior before the loop, and then store the first guess as the previous guess between that and starting the loop.

Here the only aspect that I kind of understand is that a new variable (which I’ll call previous), goes not at the end of the loop (and not even at the beginning of the loop) but before the loop. I realize that what you are suggesting here is essentially pseudo code. It helps but I guess what I am asking for now is a more explicit and detailed explanation in english describing the variables, operations, arguments, and expressions of what needs to happen in Python code. My ask is for someone to provide more lucid and explicit pseudo code for me to work with.

Here is my next iteration of my script:
import random
print("Here are the rules: \n'Guess a number between 1 and 100.' \n'We'll give you a hint if you need one.'")
num = int(random.randint(1,100))
print(num)
guess_count = int(1)
guess = int(input("Guess a number! "))
guess = previous # alot more is needed here but i'm not sure
while guess != num:
    guess_count += 1
    if abs(guess - num) <= 10:
        print("WARM")
    if abs(guess - num) > 10:
        print("COLD")
    if guess <= 0:
        print("Out of Bounds. Try again.")
    if guess > 100:
        print("Out of Bounds. Try again.")
    guess = int(input("Guess again: "))
if guess == num:
    print("You've won! It took you %d tries, but you got it. " % (guess_count))
Here are the three changes that I’ve made:
  1. At lines 10-13, I have included @ichabod801 suggested expression which returns “WARM” when the guess is within the range of 10 (higher or lower). I took it a tiny step further by telling my script to print “COLD” if the absolute difference is greater than 10.
  2. At line 9 I have replaced guess_count = guess + 1 with guess_count += 1 (to make it look cleaner).
  3. At line 7, I have initiated a previous variable as suggested by @ichabod801. This line needs a lot more work, but as I explained above, I don’t know where to begin. This is my biggest challenge.

Several times over, I’ve watched every video-lecture in Jose Portilla’s “Complete Python Bootcamp: Go from zero to hero in Python 3” Udemy course. Jose Portilla offers a second, supplementary course titled “Complete Python 3 Masterclass Journey“ where he covers the same material, but in a different context. I’m thoroughly familiar with data structures, statements, conditionals, for loops, while loops, and comparison operators. Yet I still struggle to figure out how to write my own script from scratch.

Making the jump from reading Python code to writing my own code is frustrating.

I feel like I am going nowhere fast.
Reply
#4
It can be fusterating if you know the building blocks but cannot figure out how to peice them together to make a castle. Here are a few questions I have for you:

How do you calculate the difference betweeen two values (how far apart they are)
If you wanted to track a previous guess how would you do that? Could you make an assignment during the loop somehwere that updates previous?
What does Abs() do? Why is it usefull in this situation?
How can you re-purpose abs(guess - num) <= 10 to check for the difference between guess and previous?

Keep in mind
Quote:On all subsequent turns, if a guess is
closer to the number than the previous guess return "WARMER!"
farther from the number than the previous guess, return "COLDER!"
from your rules.

Does this mean that you need to perform a different comparison depending on what turn the player is on?
How could you figure out weather it is the players first guess (is guess within +/-10 of num?) or this is not the players first guess
(compare distance of current guess to number, and distance of previous to number, which is closer? (smaller?)?

I give you these questions to get you thinking, because it seems we could give you the code but you would not know how to solve other programming challenges, but if you force yourself to think, how as a human would I do this. If I am given a number as a guess, and I am to generate my own random number, how would I check my friends guess?
Reply
#5
Okay, here's some pseudocode:

get a guess
is the guess warm or cold?
save the guess as previous
loop until correct:
    get a guess
    is it correct?
        leave the loop
    is it warmer, colder, or out of bounds?
    save the guess as previous
announce the guess count
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
(Nov-30-2018, 11:19 PM)knackwurstbagel Wrote: How do you calculate the difference between two values (how far apart they are)? If you wanted to track a previous guess how would you do that?


Perhaps: new guess minus previous guess? So: previous - guess or guess - previous?

Quote: Could you make an assignment during the loop somewhere that updates previous?

Yes. I suppose I could declare the initiate previous as guess before the loop and then from within the while loop update the value of previous (probably near the bottom).

Quote:What does Abs() do? Why is it useful in this situation?


By invoking the built in absolute function, the difference between the two numbers doesn’t matter, whether it is positive or negative. This way my script knows if the guess is within 10 integers in either direction.

Quote:How can you re-purpose abs(guess - num) <= 10 to check for the difference between guess and previous?

This is a good next step. I figure I could use: abs(guess - previous)... or abs(previous - guess)... . The next step after that is to compare one of those absolute values and see how close it is to the guess but I’m not sure how to build from there.

(Nov-30-2018, 11:19 PM)knackwurstbagel Wrote: Keep in mind
Quote:On all subsequent turns, if a guess is
  • closer to the number than the previous guess return "WARMER!"
  • farther from the number than the previous guess, return "COLDER!"
from your rules.
Does this mean that you need to perform a different comparison depending on what turn the player is on?
How could you figure out whether it is the players first guess (is guess within +/-10 of num?) or this is not the players first guess?
(compare distance of current guess to number, and distance of previous to number, which is closer? (smaller?)?

I don’t really understand very well these three questions.

Quote:I give you these questions to get you thinking, because it seems we could give you the code but you would not know how to solve other programming challenges, but if you force yourself to think, how as a human would I do this. If I am given a number as a guess, and I am to generate my own random number, how would I check my friends guess?

Thank you, @knackwurstbagel for encouraging me to figure this out on my own rather than you just giving me the answer.

@Ichabod: I re-wrote the script based on your pseudo code. Here it is:

import random
num = int(random.randint(1,100)) 
print(num)
guess = int(input("Pick a number")) # get a guess
if abs(guess - num) <= 10: # is the guess warm or cold?
	print("WARM!")
else:
    print("COLD")
previous = guess # save the guess as previous
while guess != num: # loop until correct: 
    guess = int(input("Pick another number")) # get a guess 
    if guess == num: #  is it correct?
        print("You've won! The number is %d! " % (guess)) # announce the guess count
        break # leave the loop
        ''' ugh:
    if warmer: 
        print("Warmer")
    if colder:
        print("Colder")
    '''
    elif guess <= 0:
        print("Out of Bounds. Try again.")
    elif guess > 100:
        print("Out of Bounds. Try again.")
    guess = previous #save the guess as previous
It runs without a traceback. I think what I’ve demonstrated here is a basic working understanding of Python. But lines 16-19 in particular I am still at a loss. This syntax is what I am still struggling with.

@Ichabod: Earlier you provided the Python code: abs(guess - num) <= 10. I then explained it in english. I said: “In this expression, the user’s guess is subtracted by num which is cast using an absolute value conversion (a built in function). If this absolute integer is less than or equal to 10, this means it is within the orbit of 10 integers in either direction.”

Can we reverse roles for the warmer vs colder algorithm - - where you provide the cerebral english description of the code, and I attempt to write the Python? You have already explained it english. You said:

Quote:To tell if it's warmer or colder, you will want to keep track of the previous guess. Typically you would just store the current guess as the previous guess at the end of the loop. Since there is different behavior on the first guess, you could code that behavior before the loop, and then store the first guess as the previous guess between that and starting the loop.

Thank you. This helps. But could you be twice as specific and cerebral and go into even more depth?

Thank you both, @ichabod801 and @knackwurstbagel for your continued patience as I work through this Python challenge. Thanks for your time and attention.
Reply
#7
You are on the right track but I think that my wording of
Quote:difference between guess and previous
was misleading. I should have said the difference between guess and num vs the difference between previous and num.

In your new script you are on the right track and I think all that is left is to populate the code for determining weather the new guess is Warmer or Colder. I would calculate first how far away your previous guess was, calculate how far away the new guess is, and then compare those differences to make the determination of weather you are Warmer or Colder. abs(previous - num) would be how far away the previous guess was, and you already know how to calculate the current guess.

As for my tangent on the rules you can ignore that now because you have already updated your new code to check for the first condition before the loop, thus the check inside the loop represents the 3rd rule.

Your answers are great. Keep it up.
Reply
#8
Note that line 25 should look like line 9.

Warmer/Colder: Note that you don't want the distance between guess and previous. You want to know if the current guess is further away from the correct number than the previous guess. So you want the distance between guess and num, and you want the distance between previous and num. If the guess/num distance is larger, you're getting colder. If the previous/num distance is larger, you're getting warmer. Note that they might be the same, and your instructions don't say what to do in that case. I would print 'Same temperature.'
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#9
I got my script to run beautifully! Thank you both!

@knackwurstbagel: you said:
(Dec-01-2018, 01:55 AM)knackwurstbagel Wrote: I would calculate first how far away your previous guess was, calculate how far away the new guess is, and then compare those differences to make the determination of weather you are Warmer or Colder. abs(previous - num) would be how far away the previous guess was, and you already know how to calculate the current guess.

@ichabod801: you explained something similar:
(Dec-01-2018, 02:02 AM)ichabod801 Wrote: Warmer/Colder: Note that you don't want the distance between guess and previous. You want to know if the current guess is further away from the correct number than the previous guess. So you want the distance between guess and num, and you want the distance between previous and num. If the guess/num distance is larger, you're getting colder. If the previous/num distance is larger, you're getting warmer. Note that they might be the same, and your instructions don't say what to do in that case. I would print 'Same temperature.'

Based on these descriptions of how the feature works in english, my script now looks like this:

import random
num = int(random.randint(1,100)) 
print(num)
guess = int(input("Pick a number: ")) # get a guess
if abs(guess - num) <= 10: # is the guess warm or cold?
	print("WARM!")
else:
    print("COLD")
if guess == num:
    print("You got it! The number is %d! " % (num))
previous = guess # initilize the previous vairable for later
guess_count = int(1)
while guess != num: # loop until correct: 
    guess_count += 1
    guess = int(input("Pick another number: ")) # get a guess 
    if guess == num: #  is it correct?
        print("You've won! The number is %d! " % (guess)) # announce the guess count
        print("It took you %d tries, but you got it. Congrats! " % (guess_count))
        break # leave the loop
    diff_current = abs(guess - num)
    diff_prev = abs(previous - num)
    if diff_current <= diff_prev:
        print("Warmer: You are closer now than before")
    if diff_prev <= diff_current:        
        print("Colder: You are farther away now than before")
    if guess <= 0:
        print("Out of Bounds. Try again.")
    if guess > 100:
        print("Out of Bounds. Try again.")
    previous = guess #save the guess as previous
Here are some of the changes I’ve made since last time with the most significant change first:
  1. (At lines 20-25:) I declared two variables, one for the difference between the current guess and another for the difference for the previous guess. I then proceed to compare those two variables and print “warmer” if the difference is closer and “colder” if not. This was easier than I thought it was going to be.
  2. I swapped the order of the previous guess (now line 30)
  3. I added a new conditional before the loop to account for the possibility that the user guesses the correct number on their first try (lines 9 and 10).
  4. I re-added the count feature which keeps a record of the number of times the user guesses and then prints it out when the guess is correct, as part of the congratulations to the user who wins (lines 12, 14 and 18).
It’s also worth noting that I understand now that the initial WARM/COLD (recognizing if the user’s guess is within the orbit of 10 integers in either direction) should be outside the loop because it only happens once at the beginning instead of every time the loop iterates. This resolves the problem in my initial script.

@knackwurstbagel and @ichabod801: Again, I’d like to say thanks for all your help and patience with my novice questions and misunderstandings.
Reply
#10
Some final notes: you don't need int on lines 2 and 12 (those things are already ints), and you probably don't want line 3 in the final version.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Play again, in a guessing game banidjamali 4 11,623 Jan-22-2021, 06:23 AM
Last Post: banidjamali
  Help - random number/letter guessing game juin22 1 3,181 Aug-16-2020, 06:36 AM
Last Post: DPaul
  making a guessing number game blacklight 1 2,181 Jul-02-2020, 12:21 AM
Last Post: GOTO10
  Guessing game with 4 different digits LinseyLogi 6 3,602 Mar-29-2020, 10:49 AM
Last Post: pyzyx3qwerty
  Need help with a homework problem on logical operators voodoo 3 4,576 Jun-28-2019, 03:45 PM
Last Post: jefsummers
  Functions with conditionals and comparison operators Drone4four 9 12,901 Jan-01-2019, 06:48 PM
Last Post: Drone4four
  Guessing Game "limit 4 attempts" help rprollin 3 19,699 Jun-23-2018, 04:37 PM
Last Post: ljmetzger
  Name guessing game in python Liquid_Ocelot 6 14,973 Apr-01-2017, 12:52 PM
Last Post: ichabod801
  guessing script simon 3 5,543 Oct-10-2016, 01:47 PM
Last Post: simon
  trying to get my random number guessing game to work! NEED HELP RaZrInSaNiTy 4 6,814 Oct-06-2016, 12:49 AM
Last Post: tinabina22

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020