Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Guessing game
#1
Hello everyone, I am new to python and decided to create a guessing game. So imported the random module and the user must guess a number between 1 - 9. Simple right. For some reason, I am having trouble because I created a try again function where after the user exceeds 5 tries or if they guessed the correct number the program asked them if they want to play again. I want everyone's input on what went wrong. Again I am new and am still learning, however, I am a sponge that wants to learn. Any advice is greatly appreciated! Thank you!

import random as random

i = True
guess_count = 0
leftover = 5


def try_again():
    while True:
        yes_no = input("Would you like to play again? ").lower()
        if yes_no == "yes":
            i = True
        else:
            i = False

while i: # while i is equal to true
    user_guess = int(input("Choose a number from 1 - 9: ")) # User inputs a number
    cpu_num = random.randint(1,9)

    if (user_guess != cpu_num) and (guess_count < 5): # user guess does not equal to computer number and guess count is less than 5
        if user_guess < cpu_num: # user guess is lower than computer number
            print(f"{user_guess} is too low of a guess. You have " + str(leftover) + " guesses left.")
            guess_count += 1 # increment by one
            leftover -= 1 # decrease by one
        else: # user guess is higher than computer number
            print(f"{user_guess} is too high of a guess. You have " + str(leftover) + " guesses left")
            guess_count += 1 # increment by one
            leftover -= 1 # decrease by one
    else: # if user is correct
        print("You are Dj Khaled. All you do is WIN! ") # you won
        i = False
        try_again()
        if guess_count > 5: # track the guess count
            print("Out of guesses. Would you like to try again? ") # prompt to try again
            print(cpu_num)
            i = False
Reply
#2
You are having a problem with the scope of the variable "i". I modified your try_again function to do this:
def try_again():
    while True:
        print('try_again', i)
        yes_no = input("Would you like to play again? ").lower()
        if yes_no == "yes":
            i = True
        else:
            i = False
When I run the program I see this:
Output:
Traceback (most recent call last): File "C:\Users\djhys\Documents\Python\Musings\sandbox.py", line 35, in <module> try_again() File "C:\Users\djhys\Documents\Python\Musings\sandbox.py", line 10, in try_again print('try_again', i) UnboundLocalError: local variable 'i' referenced before assignment
The program crashes because there is no variable "i" in function "try_again" until the assignment i = True or i = False. The variable "i" inside of "try_again" is local to the function, and not the same "i" assigned at the top of the script. Once you leave the function that variable disappears in a puff of smoke and you are left looking at the unaltered original "i" variable.

You could do this to tell Python you want to use a variable from outside the scope of the function:
def try_again():
    while True:
        global i  #<- Tell python I want to use i from the top of the script.
        print('try_again', i)
        yes_no = input("Would you like to play again? ").lower()
        if yes_no == "yes":
            i = True
        else:
            i = False
This lets "try_again" see the variable assigned at the top of the script, but globals should not be used to pass values out of a function. Especially not variables named "i". What is "i"? What does it mean when "i" is True? There are better ways to pass info back from the function. What if you wrote "try_again" to be like this?

def try_again():
    return input("Would you like to play again? ").lower() == "yes"
This would allow using "try_again()" as a Boolean value that tells you if the player wants to play again. The name "try_again" is a lot more meaningful than "i", and seeing it is a function you can go look at the function code to find out what the return value means (or you could read the doc string you are about to write).

There are numerous logic errors in your program. But they are logic errors, not python errors. Do you really want to test for too many guesses in the section of code that only executes when the guess is correct?
[python]
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Beginner Boolean question [Guessing game] TKB 4 2,297 Mar-22-2022, 05:34 PM
Last Post: deanhystad
  Unable to count the number of tries in guessing game. Frankduc 7 1,903 Mar-20-2022, 08:16 PM
Last Post: menator01
  Guessing game problem IcodeUser8 7 3,618 Jul-19-2020, 07:37 PM
Last Post: IcodeUser8
  Beginner Code, how to print something after a number of turns (guessing game) QTPi 4 2,740 Jun-18-2020, 04:59 PM
Last Post: QTPi
  Python Help - Guessing Game JamieT 5 2,765 Apr-16-2020, 01:30 PM
Last Post: deanhystad
  Help for guessing game code Kronos 5 3,283 Mar-09-2020, 04:53 PM
Last Post: snippsat
  guessing the number game go127a 6 4,838 Apr-27-2019, 01:23 PM
Last Post: go127a
  Guessing Game does not work the_entrepreneur 3 2,795 Apr-20-2019, 06:19 AM
Last Post: SheeppOSU
  Guessing Game with .WAV Files - Python Coding NonEntity 8 4,349 Nov-20-2018, 12:53 AM
Last Post: NonEntity
  Need help with simple guessing game! ghost0fkarma 2 2,805 Nov-03-2018, 01:19 AM
Last Post: ghost0fkarma

Forum Jump:

User Panel Messages

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