Python Forum
Need help with simple guessing game! - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Need help with simple guessing game! (/thread-13836.html)



Need help with simple guessing game! - ghost0fkarma - Nov-02-2018

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!


RE: Need help with simple guessing game! - j.crater - Nov-02-2018

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.


RE: Need help with simple guessing game! - ghost0fkarma - Nov-03-2018

(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!