Python Forum
Need help with simple guessing game!
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Need help with simple guessing game!
#1
import random


def game(ranNum, numGuesses=10):
    pick = int(input("Enter a number ---->  "))
    if pick > ranNum:
        print("Too high try again. " + str(numGuesses - 1) + " trys remaining")
        numGuesses -= 1
        game(ranNum)
    elif pick < ranNum:
        numGuesses -= 1
        print("Too low try again. " + str(numGuesses - 1) + " trys remaining")
        game(ranNum)
    elif pick == ramNum:
        print("You Won! With a total of " + str(numGuesses) + " trys remaining")
       
game(random.randint(0, 100))
Anytime I guess a number, the output is always 9 trys remaining. I would like it to count down from 10 to 0. Any help is appreciated!
Reply
#2
That's because in if/elif statements you call game() without numGuesses parameter, which means it will always be 10 (default).
So instead do this
game(ranNum, numGuesses)
in lines 9 and 13.
As an extra suggeston: what you are doing is calling functions recursively. You would get a much safer and "cleaner" code by using a while loop instead.
Reply
#3
(Nov-02-2018, 10:13 PM)j.crater Wrote: That's because in if/elif statements you call game() without numGuesses parameter, which means it will always be 10 (default). So instead do this
 game(ranNum, numGuesses) 
in lines 9 and 13. As an extra suggeston: what you are doing is calling functions recursively. You would get a much safer and "cleaner" code by using a while loop instead.
Thank you very much good sir!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Beginner Boolean question [Guessing game] TKB 4 2,310 Mar-22-2022, 05:34 PM
Last Post: deanhystad
  Unable to count the number of tries in guessing game. Frankduc 7 1,910 Mar-20-2022, 08:16 PM
Last Post: menator01
  Guessing game problem IcodeUser8 7 3,635 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,745 Jun-18-2020, 04:59 PM
Last Post: QTPi
  Python Help - Guessing Game JamieT 5 2,776 Apr-16-2020, 01:30 PM
Last Post: deanhystad
  Simple cards game blackpanda 3 4,252 Apr-10-2020, 08:46 PM
Last Post: TomToad
  Guessing game kramon19 1 2,181 Mar-25-2020, 04:17 AM
Last Post: deanhystad
  Help for guessing game code Kronos 5 3,289 Mar-09-2020, 04:53 PM
Last Post: snippsat
  guessing the number game go127a 6 4,855 Apr-27-2019, 01:23 PM
Last Post: go127a
  Guessing Game does not work the_entrepreneur 3 2,806 Apr-20-2019, 06:19 AM
Last Post: SheeppOSU

Forum Jump:

User Panel Messages

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