Python Forum

Full Version: Need help with simple guessing game!
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!
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.
(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!