0

So I've typed this up and I've gone over it for a couple of hours now and I can't seem to understand what is wrong with it. When I run it and I pick a choice, it just quits. I've used IDLE to run it and in order to run the functions dice () or guess () I have to do it manually. Thanks in advance

from random import randint

def main ():
    print ("Choose a game.")
    print ("1. Dice")
    print ("2. Guess")
    choice = input ("Enter your choice: ")

    if choice == 1:
        dice ()
    elif choice == 2:
        guess ()
    elif choice == 'Q' or choice == 'q':
        exit ()


def dice ():
    rolling = True
    while rolling:
        n = input ("How many dice? ")
        if n == 'M' or n == 'm':
            main ()
        elif n == 'Q' or n == 'q':
            exit ()
        else:
            for i in range (int (n)):
                print (randint (1, 6))


def guess ():
    guessing = True
    while guessing:
        print ("Guess the number: 1-1000")
        n = randint (1, 1000)
        count = 0
        wrong = True
        while wrong:
            g = input ("Guess: ")
            if g == 'M' or g == 'm':
                main ()
            elif g == 'Q' or g == 'q':
                exit ()
            else:
                if int (g) > n:
                    print ("Lower")
                    count += 1
                elif int (g) < n:
                    print ("Higher")
                    count += 1
                else:
                    print ("Correct")
                    count += 1
                    wrong = False
                    print ("You took " + str (count) + " guesses")


main ()
feetus
  • 1
  • 1
    Your input from `input` is always going to be a string. If you want choice to be an `int`, try `if int(choice) == 1`. As an addendum, you might save yourself some headaches if you have an `else` under your `elif`s that prints `Wow I didn't expect this option` so you know where to dig around. As another addendum, don't put a space between your function names and the parentheses. `exit()` – MoxieBall Jun 20 '18 at 18:41
  • `if choice == '1':` and `elif choice == '2'` - input delivers a string. No need to invoke `int()` on it, it will only throw valueerrors if someone inputs a non-number like `"Q"`. – Patrick Artner Jun 20 '18 at 18:42
  • @MoxieBall as `'Q'` is a valid input, using `int()` will cause ValueErrors. Compare against `'1'` && `'2'`string. – Patrick Artner Jun 20 '18 at 18:44
  • if you just do `choice = input ("Enter your choice: ").upper()` so your input is upper()ed once you can leave off all the secondary comparisions against the lower()ed characters – Patrick Artner Jun 20 '18 at 18:45
  • Thanks a bunch! That totally slipped my mind. – feetus Jun 20 '18 at 18:49
  • @PatrickArtner Yes, didn't think too hard about that, just wanted to explain that the types were not what were expected. – MoxieBall Jun 20 '18 at 18:49
  • Also you should think about your programflow - if you input 1,M,1,M,1,M,1,M,1,M you are going ever deeper into functions that call functions with endless loops that call the first function that calls the other function and in its andless loop it calls the first function that ...... Its better to break from a endless loop and return to some "general staging function" that then can be left via Q - this way you are stacking call frames into call frames into ....... put the while true inside your main() and dont call main() from your other functions but simply end them/return to main() – Patrick Artner Jun 20 '18 at 18:52
  • Possible duplicate of [How to check if string input is a number?](https://stackoverflow.com/questions/5424716/how-to-check-if-string-input-is-a-number) – Olivier Melançon Jun 20 '18 at 19:03

2 Answers2

0

As pointed out in comments, the problem is caused because input returns a string, but you are checking for equivalence to integers. The following code should work:

def main ():
    print ("Choose a game.")
    print ("1. Dice")
    print ("2. Guess")
    choice = input ("Enter your choice: ")

    if choice == '1':
        dice ()
    elif choice == '2':
        guess ()
    elif choice == 'Q' or choice == 'q':
        exit ()
Artemis
  • 2,553
  • 7
  • 21
  • 36
0

I fixed the comparison error as pointed out in my comment. Optimized the program flow so you do not get ever deeper into function call stacks as pointed out in the other one:

from random import choices, randint

def quit():
    exit(0)     

def myInput(text):
    """Uses input() with text, returns an int if possible, uppercase trimmed string else."""
    p = input(text).strip().upper()
    try:
        p = int(p)
    except ValueError:
        pass

    return p

def dice ():
    while True:
        n = myInput ("How many dice? ")
        if n == 'M':
            break  # back to main() function
        elif n == 'Q':
            quit() # quit the game
        elif isinstance(n,int):  # got an int, can work with that
            # get all ints in one call, print decomposed list with sep of newline
            print (*choices(range(1,7), k = n), sep="\n")
        else: # got no int, so error input
            print("Input incorrect: Q,M or a number accepted.")


def guess ():
    while True:
        print ("Guess the number: 1-1000")
        n = randint (1, 1000)
        count = 0
        while True:
            g = myInput ("Guess: ")
            if g == 'M':
                return  # back to main menue
            elif g == 'Q':
                quit () # quit the game
            elif isinstance(g,int): # got a number, can work with it
                count += 1
                if g != n:  # coditional output, either lower or higher
                    print ("Lower" if g < n else "Higher")
                else:
                    print ("Correct")
                    print ("You took {} guesses".format(count))
            else: # not a number, incorrect
                print("Input incorrect: Q,M or a number accepted.")



# which function to call on which input
options = { "1" : dice, "2" : guess, "Q":quit }

def main ():
    while True:
        print ("Choose a game.")
        print ("1. Dice")
        print ("2. Guess")
        choice = input ("Enter your choice: ").upper()

        if choice in options:
            options[choice]()  # call the function from the options-dict
        else:
            print("Wrong input.")

main ()
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69