Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Guess a number game
#1
I’m trying to write a guessing game where the computer chooses a number between 1 and 100 and it’s up to the user to guess what the number is. It’s part of a Udemy course I am taking.

The task is for practicing using while loops.

Here the challenge directly from the course instructor's Jupyter Notebook:
Quote: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!
I can scratch off #1 and #4 because I have effectively implemented them. I am struggling with #2 and #3. Before we address #2 and #3, let’s address the ways in which my code is already problematic. Here is my code:

import random
print("Here are the rules: /nGuess a number between 1 and 100. We'll give you a hint if you need one.")
num = int(random.randint(0,101))
print(num)
guess_list = int(1)
guess = int(input("Guess a number! "))
while guess != num:
    guess_list = guess_list + 1
    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_list))
Here is how the script runs in my Jupyter Notebook: https://i.imgur.com/yJvKsk2.png

Here are the problems with my code (in order from least significant to most significant):
  1. I add a new line character to the first string. But when the rules are actually printed in the output, a new line is not entered, why? What is wrong with the way I am trying to add a new line?
  2. The first line of output should reflect the order in which operations are declared in the script. For example line 2 prints the rules, line 4 prints the numbers and line 6 prompts the user for an integer. So these operations should transpire in that order. But instead, in the output first the user is prompted. Why is the user prompted to enter a number when that shouldn’t happen until after the rules are printed and the random integer is generated?
  3. Notice the “In [ * ]”? That indicates that the script is stuck in a loop. Usually when this happens, my Jupyter Notebook is frozen however in my case the script continues to run without an issue until I interrupt the kernel, which then produces the following traceback. What is this ugly traceback trying to say?
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
/usr/lib/python3.7/site-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password)
    728             try:
--> 729                 ident, reply = self.session.recv(self.stdin_socket, 0)
    730             except Exception:

/usr/lib/python3.7/site-packages/jupyter_client/session.py in recv(self, socket, mode, content, copy)
    802         try:
--> 803             msg_list = socket.recv_multipart(mode, copy=copy)
    804         except zmq.ZMQError as e:

/usr/lib/python3.7/site-packages/zmq/sugar/socket.py in recv_multipart(self, flags, copy, track)
    466         """
--> 467         parts = [self.recv(flags, copy=copy, track=track)]
    468         # have first part already, only loop while more to receive

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.recv()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket.Socket.recv()

zmq/backend/cython/socket.pyx in zmq.backend.cython.socket._recv_copy()

/usr/lib/python3.7/site-packages/zmq/backend/cython/checkrc.pxd in zmq.backend.cython.checkrc._check_rc()

KeyboardInterrupt: 

During handling of the above exception, another exception occurred:

KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-2-c26f06c026cc> in <module>()
      4 print(num)
      5 guess_list = int(1)
----> 6 guess = int(input("Guess a number! "))
      7 while guess != num:
      8     guess_list = guess_list + 1

/usr/lib/python3.7/site-packages/ipykernel/kernelbase.py in raw_input(self, prompt)
    702             self._parent_ident,
    703             self._parent_header,
--> 704             password=False,
    705         )
    706 

/usr/lib/python3.7/site-packages/ipykernel/kernelbase.py in _input_request(self, prompt, ident, parent, password)
    732             except KeyboardInterrupt:
    733                 # re-raise KeyboardInterrupt, to truncate traceback
--> 734                 raise KeyboardInterrupt
    735             else:
    736                 break

KeyboardInterrupt:
For my future reference, the course material I am working with in this thread can be found on the teacher’s GitHub page (Jose Portilla). Here is the repo’s top level directory. The module I am working on is 02-Python Statements > 09-Guessing Game Challenge.ipynb. Here is my progress tracked on my forked repository.
Reply
#2
Well, there's a bit going on here.

The new line is not being entered because it is not typed correctly. It's "\n", not "/n".

On line 3, randint() is inclusive. So, there is the possibility of setting "num" to 0 or 101.

On line 5, "guess_list" is misleading. When I read that name, I was immediately confused about it being an integer. The variable's identifier suggests that it's a list and it isn't. Renaming would be a good idea.

Lines 9 and 11 can be merged into one:

if guess <= 0 or guess > 100:
I don't know what's going on with Jupyter Notebook; I never bothered to use it despite its popularity.
Reply
#3
(Nov-16-2018, 12:04 AM)stullis Wrote: The new line is not being entered because it is not typed correctly. It's "\n", not "/n".

I should have mentioned that I tried both a forward-slash and back-slash which showed the same problem. But I just tried a backslash a second time and it works fine now. Thanks for the clarification.

Quote:On line 3, randint() is inclusive. So, there is the possibility of setting "num" to 0 or 101.

I thought randint() was similar to slicing a string or other iterable where it is exclusive. I have change my randint() function call parameters from 0,101 to 1,100.

Quote:On line 5, "guess_list" is misleading. When I read that name, I was immediately confused about it being an integer. The variable's identifier suggests that it's a list and it isn't. Renaming would be a good idea.

That is an excellent point. I have renamed my guess_list to guess_count.

Quote:Lines 9 and 11 can be merged into one:
if guess <= 0 or guess > 100:
This is another terrific suggestion.

Here is my new script with all of the above changes implemented:
import random
print("Here are the rules: \n'Guess a number between 1 and 100. 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! "))
while guess != num:
    guess_list = guess_count + 1
    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))
Much improved, eh?

Quote:I don't know what's going on with Jupyter Notebook; I never bothered to use it despite its popularity.

It runs perfectly natively in my python interpreter now. When I copied the code back over to my Jupyter Notebook, it ran really well too. I figure the In [*]: feature in the Jupyter Notebook indicates that the script is still running because it's still prompting the user for more input. Once the script is finished, then the In [*]: turns into In [1]: like I'd expect. There is no need to interupt or restart the kernel. The order in which the lines are called now reflect the order as they appear in the code. And there is no longer an ugly traceback. I have no idea what I changed which fixed these issues, but they are fixed. Edit: I spoke to soon. The unusual behaviour and performance has returned. Looks like I will begin playing with scripts in my unix shell going forward.

If anyone else who may have more experience with Jupyter Notebooks and can identify what is going on here, that would be nice.

Thanks you @stullis for you help so far. I will return here soon with follow up questions about the initial challenge that I am still having difficulty with.
Reply
#4
Line 8 still references guess_list, by the way.
Reply
#5
(Nov-16-2018, 02:47 AM)stullis Wrote: Line 8 still references guess_list, by the way.

Thanks. I've updated my script.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Help - random number/letter guessing game juin22 1 3,193 Aug-16-2020, 06:36 AM
Last Post: DPaul
  Dynamically chosing number of players in a "game" nsadams87xx 5 4,154 Jul-17-2020, 02:00 PM
Last Post: deanhystad
  Can someone help me optimize this game for large number of strings Emekadavid 13 4,929 Jul-06-2020, 06:16 PM
Last Post: deanhystad
  making a guessing number game blacklight 1 2,193 Jul-02-2020, 12:21 AM
Last Post: GOTO10
  Guess the number game jackthechampion 5 3,178 Mar-07-2020, 02:58 AM
Last Post: AKNL
  Asking for help in my code for a "Guess the number" game. Domz 5 3,812 Aug-14-2019, 12:35 PM
Last Post: perfringo
  guess the number atux_null 8 6,084 Dec-06-2017, 09:14 AM
Last Post: gruntfutuk
  trying to get my random number guessing game to work! NEED HELP RaZrInSaNiTy 4 6,852 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