0

I'm currently working on an assignment for my intro python class in school. The program is a "guess my number" variant, but its focus is on global variables and the try/except operation. I've managed to figure out most of it, but I'm having trouble calling my function that gives a random number. Choice 1 and 2 should use two different secret numbers, so I thought a function was the way to go, but I'm getting an error, TypeError: unorderable types: int() > function(). I've tried making everything int(), but that wasn't working. I'm not sure how to get my program to talk to my function correctly, and I cant find much info about how to fix unorderable types in our book or on the web. any suggestions or ideas would be helpful.

def secret (secret):
    from random import randint
    secret = randint (1, 10)
    return secret


# first function will be for the menu( just like last homework assignment)
def menu_choice():
    print("Guess the number")#any answers to this should be checked by try/except function for a number
    print("0: Exit")  #this should exit the loop and end the program
    print("1: Guess") #this should go into the guess the number function/program
    print("2: Get a new secret number")#not sure how this will work

    return input("Enter your selection:   ")

#setting my flags
loop = 1
choice = 0

while loop == 1:
    # this try/except should weed out any non numeric answers. the choices will limit users
    #to 0,1,2 and the else statement will remind them of their choices.
    try:
        choice = int(menu_choice())
    except ValueError:
        print(" The choice must be 0, 1, or 2. Please try again.")

    if choice == 1:
        guess = 0
        while guess != secret:
            guess = (input(" Please guess a number between 1 and 10.   "))
            #this try/except will do the same as above, but the first "if" statement below will handle
            #any numbers outside the stated parameters of 1-10.
            try:
                guess = int(guess)
            except ValueError:
                print("That wasn't a number between 1 and 10. Please try again.    ")
            else:
                if guess < 1 or guess > 10:
                    print(" The guess needs to be between 1 and 10.  ")
                elif guess > secret:
                    print("Too high!")
                elif guess < secret:
                    print("Too low!")
        print("             ****** That's correct! The number was", secret , "******")

    elif choice == 2:
    # not sure how to reset the randint, so i'm resorting to making choice 2 the 
    #same as choice 1. this isn't correct, because its calling the same randint,
    #and getting the same secret number. need to try to make randint/secret
    #a function so it erases the number after the choice is done with it.
        guess = 0
        while guess != secret:
            guess = (input(" Please guess a number between 1 and 10.   "))
            try:
                guess = int(guess)
            except ValueError:
                print("That wasn't a number between 1 and 10. Please try again.    ")
            else:
                if guess < 1 or guess > 10:
                    print(" The guess needs to be between 1 and 10.  ")
                elif guess > secret:
                    print("Too high!")
                elif guess < secret:
                    print("Too low!")
        print("             ****** That's correct! The number was", secret,  "******")

    elif choice == 0:
        print("Thank you for playing.")
        loop = 0

    else:
        print("Please choose 0, 1, or 2. ")
3
Contributors
6
Replies
67
Views
3 Years
Discussion Span
Last Post by cobaltbravo
0
from random import randint

def pick_secret():
    secret = randint(1, 10)
    return secret

secret = pick_secret()

print(secret)  # test

You have to call your function somewhere in your code. Do not use the same name for function and variable. Are you using Python3 or Python2?

0

I'm using version 3. Thanks for pointing out the naming issue, I'm not very experienced with functions yet. I tried following your suggestion and taking the "import randint" out of the function, changed my function's name, and tried to move the "secret = pick_secret()" down to right before the while loop, but python doesn't seem to like that. How can I arrange it so python knows to look at secret = pick_secret at just the right time? I tried changing all the secret into pick_secret so it would just call on the function for the number, but it gave me another unorderable error. I think I only want to call the pick_secret function once per choice so it doesn't change the value every time it checks the guess against the secret, but I don't know how to make it work the way I need it to. My apologies if this sounds confusing, but I am rather confused.

0

but I am rather confused

Yes that's normal when you new to programming.
Some help,you are writing more code than you need for this and it's a little messy.
Forget errohandling(try,except),function this can you do later.
Her is the basic of the game,look at code and see if it make any seense.

import random

secret_number = random.randint(1,10)
guess = 0
while guess != secret_number:
    guess = int(input("Take a guess: "))
    if guess > secret_number:
        print ("Lower")
    elif guess < secret_number:
        print ("Higher")
print('You guessed it! The number was {}'.format(guess))

You can do error checking,but don't mess code up to much.
Game code you can put in one fuction.

Here is a simple menu function that loop,you will always fall back into this menu.
Here you can start a new game or quit.
Try to type lot of mess,you see that it cacth all error with a simple else block(no try,except)
For other input types like(int,float) you may need(try,except),but dont overuse it.
Traceback in Python are very clear and not dangerous for any user.

def game():
    '''Code for game'''
    Print('You now in game function')
    input('Press enter to return to menu')    

def menu():
    while True:
        print('(1) Play guess game')
        print('(q) Quit')
        choice = input('Enter your choice: ')
        if choice == '1':
            game()
        elif choice.lower() == 'q':
            return False
        else:
            print('Not a correct choice: {} try again'.format(choice))

if __name__ == '__main__':
    menu()

"import randint" out of the function,

Rember this,import statement shall always be on top.

Edited by snippsat

0

unfortunately, I have to have a lot of the mess in there for what our teacher wants. the focus of the assignment is on global variables(randint) and try/except(error handling). My menu is exactly want the teacher said he wanted, my problem lies in keeping the random number function global, and being able to call it for a new random number for both choice 1 and 2.

0

unfortunately, I have to have a lot of the mess in there for what our teacher wants. the focus of the assignment is on global variables(randint) and try/except(error handling)

No you can stucture your code better,i don't think your teacher want you to write as you do in first post.
Here is an example of try/except,as you see i make a function for it.
An game code still look clean an nice.

import random

def user_input():
    '''Function to make sure that integers are used'''
    while True:
        try:
            guess = int(input("Take a guess: "))
            return guess
        except ValueError:
            print('Only numbers as input,try again')

secret_number = random.randint(1,10)
guess = 0
while guess != secret_number:
    guess = user_input()
    if guess > secret_number:
        print ("Lower")
    elif guess < secret_number:
        print ("Higher")
print('You guessed it! The number was {}'.format(guess))

Edited by snippsat

0

After asking some classmates for advice, I finally got the program to work how I think the teacher wants it to. It has the try/except blocks and the global variable the teacher wanted, and it works. Thanks everyone for your suggestions. here it is.

# this should bring a random number when the variable secret is used.
from random import randint
secret = randint (1, 10)



# first function will be for the menu( just like last homework assignment)
def menu_choice():
    print("Guess the number") #any answers to this should be checked by try/except function for a number
    print("0: Exit") #this should exit the loop and end the program
    print("1: Guess") #this should go into the guess the number function/program
    print("2: Get a new secret number") #this should recall the randint to get a new secret number

    return input("Enter your selection:   ")

#setting my flags
loop = 1
choice = 0

# the begining of my overall while loop
while loop == 1:
    # my first try/except block. this will catch anything other than the correct menu choices
    try:
        choice = int(menu_choice())
        if choice == 0:
            print("Thank you for playing.")
            loop = 0   
        elif choice == 2:
            # this resets the secret number by calling it again. this was the hardest part to figure out
            secret = randint (1, 10)
        elif choice == 1:
            guess = 0
            # where my number guessing while loop starts
            while guess != secret:
                #the second try/except, that will catch anything other than 1-10. the int will throw the
                # input to the except if its not a numeric value
                try:
                    guess = int(input(" Please guess a number between 1 and 10.   "))
                    if guess < 1 or guess > 10:
                        print(" The guess needs to be between 1 and 10.  ")
                    elif guess > secret:
                        print("Too high!")
                    elif guess < secret:
                        print("Too low!")
                 # the exception for the number guess
                except ValueError:
                    print("******  I'm sorry, that wasn't a number between 1 and 10. Please try again!  ******")

            print("             ****** That's correct! The number was", secret , "******")

        else:
            print("******  Please choose 0, 1, or 2.  ****** ")
     # the exception for the menu choice try       
    except ValueError:
        print("******  I'm sorry, the choice must be 0, 1, or 2. Please try again.  ******")    
This question has already been answered. Start a new discussion instead.
Take the time to help us to help you. Please be thoughtful and detailed and be sure to adhere to our posting rules.