954,160 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Ahh ya it would work, if I did not have a cluster F$%! of code...Here is what it looks like from THAT function down.

def Tav():
    global gold
    print 'Hello There! Welcome to the Tavern!\n'
    print 'Here you can purchase some beer or liquor!\n'
    print 'You currently have',gold,'Gold\n'

    print '1)Beer 10$'
    print '2)Liquor 20$'
    print '3)Exit\n'
    print 'Enter 1, 2, 3\n'

    try:
        choice = int(raw_input('What will it be? '))
    except ValueError:
        print 'Invalid Input! Please input only numbers.\n'
        Tav()
    else:
        if choice in [1, 2]:
            global price

            if choice == 1:
                price = 10
                if gold >= price:
                    gold -= price
                    print 'You bought a beer!\n'
                    print 'You now have',gold,'Gold\n'
                    Tav()
                elif gold < price:
                    print 'You do not have enough gold!'
                    Tav()

            if choice == 2:
                price = 20
                if gold >= price:
                    gold -= price
                    print 'You bought a shot of liquor!\n'
                    print 'You now have',gold,'Gold\n'
                    Tav()
                elif gold < price:
                    print 'You do not have enough gold!'
                    Tav()

def Gold():
    global gold

def Rep():
    global rep
    global gold
    rep = rep + 1
        
    print 'You have gained more reputation!\n'
    print 'Your Reputation is now:',
    print rep



def main():
    choice = 0
    loop = 1
    while loop == 1:
    
        print 'Welcome to Pirates!\n'
        print 'Please Pick one of the following options!\n'
    
        print 'Type the options as shown!\n'
        print '1)Type: 1 to enter the Shipyard!'
        print '2)Type: 2 to enter the Tavern!'
        print '3)Type: Coming Soon!'
        print '4)Type: Coming Soon!'
        print '5)Type: 5 to exit\n'
        choice = raw_input('Input an option! \n')

        if choice == '1':
            S()

        elif choice == '2':
            Tav()

        elif choice == '5':
            print 'You have quit the game.'
            loop = 0

        else:
            print 'Invalid Input! Please type a Number!'
            
if __name__=='__main__':
    main()
Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

This doesn't even incorporate the suggestion I gave, but still contains the unwanted recursion (see lines 12 to 16, along with 27, 30, 38, 41).

You would have to change the Tav function to:

def Tav():
    global gold
    print 'Hello There! Welcome to the Tavern!\n'
    print 'Here you can purchase some beer or liquor!\n'
    print 'You currently have',gold,'Gold\n'

    print '1)Beer 10$'
    print '2)Liquor 20$'
    print '3)Exit\n'
    print 'Enter 1, 2, 3\n'

    while True:
        try:
            choice = int(raw_input('What will it be? '))
        except ValueError:
            print 'Invalid Input! Please input only numbers.\n'
        else:
            break

    # this now gets executed after "break" is made.
    if choice in [1, 2]:
        # etc...

And even then, you make a couple more calls to the Tav function further down, leading to that recursion thing I told you about. You should be able to figure out a way of changing that :P

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Ok I had bad indention is why the it would not work with another loop. But now when I use that 'break' you put after else. It ignores the 'if' statments down below and when I type a number it just ignores it.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

I can only assume that you put the indentation level of the if statements so that they were inside the loop. They should be outside of that while loop, like I had in my above code.

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Good call...lol

EDIT, well no that might have been one problem but fixing that threw all kinds of errors..damn.. It did not like un- indenting that lol

Ok one problem is where I put 'choice = int raw_input' and so on..
on down I call choice as 'if choice in [1, 2, 3]: it throws a name error choice not defined because its out of the loop that the original choice is in..

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Ok, never mind, I un-indented to far. fixed and works right now =)
Thank you Shadwick! If I only had your brain...lol

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Ok that loop works but it does not do what is needed, the code I had did exactly what was needed, but as you said, it repeated. That while loop in the Tav() function now screws up the functions above and also dose not loop properly within the function, it just loops the choice, not the whole menu which was the point of the function.. So now I dont know.. I knew what I was doing, when it was my code, but now im lost again...

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Well if you wanted it to re-print your menu every time, you'd just need to stick all those print statements from above that while loop to inside it, right on top of that choice = raw_input... part.

As for "messing up the functions above", what exactly do you mean? I can only really answer your questions when you be specific with them, and if there are errors, also show the traceback it gives.

If you wanted Tav to loop the entirety of itself, you can contain its contents within a large while loop, or you could place the call to it from the other part of code within a while loop.

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Here is the function above Tav() I want it to do the same as Tav() I set them both up identical but I can not get this one to exit even tho I put a break it still loops..

def S():
    while True:
        global gold
        print 'Welcome to the Shipyard!\n'
        print 'Here you can buy new Ships.\n'
        print 'You currently have',gold,'Gold.\n'
    
    
        Shiplist = {'1)Sloop':'1500$', '2)Schooner':'3500$', '3)Brigantine':'6500$', '4)Galley': '9500$'}
        print 'The current Ships avaliable:\n'
        print Shiplist
        print ' '
        print 'To Exit type 5'
        print 'Type a number to choose the corresponding Ship!\n'
    
    
        try:
            choice = int(raw_input('Enter Number: '))
        except ValueError:
            print 'Invalid Input! Please input only numbers.\n'
        
    
        
        if choice in [1, 2, 3, 4]:
            global price
            global ship
        

        if choice == 1:
            ship = 'Sloop'
            price = 1500

        elif choice == 2:
            ship = 'Schooner'
            price = 3500

        elif choice == 3:
            ship = 'Brigantine'
            price = 6500

        elif choice == 4:
            ship = 'Galley'
            price = 9500
            

        if gold >= price:
            print 'You bought a new ship!'
            gold -= price
            print 'You now have:',
            print gold,
            print 'Gold\n'
                

        elif gold < price:
            print 'You do not have enough Gold!'
            print 'Try again later!\n'
                

        elif choice == 5:
            break
Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Oh... this code looks fairly um, interesting. There are a number of things that should be changed.

It would be best to indent the lines 2- 57 in one level so that they're under the if that triggers if the input is 1 - 4.

The problem that this should also solve is the "elif choice == 5: break". The issue is that because you put lines 46-56 in that same level as those "choice" ifs, the breaking conditional is now linked as an elif for the "if gold >= price" statement.

Your code should be something like:

# ...
        try:
            choice = int(raw_input('Enter Number: '))
        except ValueError:
            print 'Invalid Input! Please input only numbers.\n'

        if choice in [1, 2, 3, 4]:
            global price
            global ship
            # I indented this below
            if choice == 1:
                ship = 'Sloop'
                price = 1500

            elif choice == 2:
                ship = 'Schooner'
                price = 3500

            elif choice == 3:
                ship = 'Brigantine'
                price = 6500

            elif choice == 4:
                ship = 'Galley'
                price = 9500
                
            if gold >= price:
                print 'You bought a new ship!'
                gold -= price
                print 'You now have:',
                print gold,
                print 'Gold\n'
                    
            elif gold < price:
                print 'You do not have enough Gold!'
                print 'Try again later!\n'
            # ...all the way to here.

        elif choice == 5:
            break

elif links the statement to the most recentif statement on the same level of indentation as it. All that part that I indented only happens if the choice is 1 - 4 anyways, so it should go under that if choice in [1,2,3,4] statement.

The "break" part is now linked as anelif to the if choice in [1,2,3,4] statement because it is the most recentif statement of the same indentation level.

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Ok as you said.. I believe.. But It still when option 5 is inputed, it still prints out 'You do not have enough gold' & 'Try again later' statments.. and then loops back to enter the number again.

def S():
    while True:
        global gold
        print 'Welcome to the Shipyard!\n'
        print 'Here you can buy new Ships.\n'
        print 'You currently have',gold,'Gold.\n'
    
    
        Shiplist = {'1)Sloop':'1500$', '2)Schooner':'3500$', '3)Brigantine':'6500$', '4)Galley': '9500$'}
        print 'The current Ships avaliable:\n'
        print Shiplist
        print ' '
        print 'To Exit type 5'
        print 'Type a number to choose the corresponding Ship!\n'
    
    
        try:
            choice = int(raw_input('Enter Number: '))
        except ValueError:
            print 'Invalid Input! Please input only numbers.\n'
        
    
        
        if choice in [1, 2, 3, 4, 5]:
            global price
            global ship
        

            if choice == 1:
                ship = 'Sloop'
                price = 1500

            elif choice == 2:
                ship = 'Schooner'
                price = 3500

            elif choice == 3:
                ship = 'Brigantine'
                price = 6500

            elif choice == 4:
                ship = 'Galley'
                price = 9500
            

            if gold >= price:
                print 'You bought a new ship!'
                gold -= price
                print 'You now have:',
                print gold,
                print 'Gold\n'
                

            elif gold < price:
                print 'You do not have enough Gold!'
                print 'Try again later!\n'
                

        elif choice == 5:
            break


I know its something stupid I am not seeing, after this im going to bed, because I am nothing thinking clearly..

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

That is due to line 24:

if choice in [1, 2, 3, 4, 5]:

You allow 5 to execute the 'buying-a-ship'if statement instead of the break one. It should just be:

if choice in [1, 2, 3, 4]:  # no 5!
shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Okay, that fixed it..As said, I am going to bed as I am nothing thinking logic but more idiot right now.. So thank you again. and good nite lol

I will update this tomorrow with some more functions I think you might like...I think I understand the 'if' and 'elif' better now in loops.. and also where I use 'choice in'. Good stuff here..And you also help me learn from my stupid mistakes.. Maybe one day I can get them classes down.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

I followed the examples you set last night for 'loops', and things. Today I added a 'Merchant'. So now you can buy a few goods, sell goods you have. the price right now is always the same, I will change this later with a random.randrange so sometimes you may pay more or less, and the items may sell for more or less..

This would rock if it was in a GUI form...maybe not graphics that good, but buttons would be a nice addition sometime..

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

I got pretty much everything lined out except I get an error, here is the error code..

File "C:\Python25\pirates.py", line 35, in S
if choice in [1, 2, 3, 4]:
UnboundLocalError: local variable 'choice' referenced before assignment

Ok I am not sure why its throwing that up, has not done that before, only dose it when I try and make it error by not typing a number.. You can reference my code I have not changed the way its typed or formatted, just exceptions..

try:
            choice = int(raw_input('Enter Number: '))
        except ValueError:
            print 'Invalid Input! Please input only numbers.\n'
        
    
        
        if choice in [1, 2, 3, 4]:
            global price
            global ship
        
Do I just need to make it 'except' an UnboundLocalError?
            if choice == 1:
Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

Well if the try ... except block isn't in a while loop, with that else: break segment I posted for you before, then there's your problem.

If you give bad input, it will error and go to the "Invalid Input!..." line, and then continue on down the script to the if choice in [1,2,3,4] statement.
But if it threw an error,choice is still undefined, yet it tries to compare it in that if statement. The reason it is still undefined is because it caused an error when trying to assign a value to it, so it stayed undefined.

I showed you a solution before, which was the while loop to get input until it gets good input, in which case it breaks out and continues down the script:

while True:
    try:
        choice = int(raw_input('Enter Number: '))
    except ValueError:
        print 'Invalid Input! Please input only numbers.\n'
    else:  # if the input doesn't cause an error
        break

# that 'break' will make it continue along to here... (outside of the loop)
if choice in [1, 2, 3, 4]:
    # etc.
shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

Well, I thought we had to drop the 'else' statement because I needed all the 'if' and 'elif' functions to be under the loop in order to return to the menu? It was on page 3 when you fixed the indention problem for that to work.. I throw the else statement in there I gotta remove the 'ifs' from the loop in order for it to pass..Which then the menu dose not work.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

You're not understanding: the else with the break is attached to the try/except block. That is inside the while loop. Then, outside the loop, on the starting on the same indentation level as your loop, goes all the stuff that happens after the input segment.

No offense, but please, please, please read some books on basic Python or programming in general and do some simple exercises pertaining to that. You need to understand how the code I gave in my previous post actually works.

It's simple: the while loop begins, and asks the user for input. If it's bad (i.e. a non-number), then it goes to the except block, and because of that, it does not execute that else: break section. This means that it asks for input again, and so forth. If it gets good input, then it won't cause an error, so it will go to the else: break part. This break ends the while loop, this allowing the script to continue execution downwards where it encounters the stuff you have dealing with handling the choice the user gave.

I honestly cannot get any more simplistic than that...

shadwickman
Posting Pro in Training
497 posts since Jul 2007
Reputation Points: 186
Solved Threads: 77
 

I think we are both on two different pages here..

try:
            choice = int(raw_input('Input a Number! '))
        except ValueError:
            print 'Invalid Input, Please type a Number!\n'
        # this must be where it is at!
        if choice in [1, 2, 3]:

This above, MUST be in line with the loop/try statement. Otherwise its a waste of time, because it must loop. Doing what you said, puts the 'ifs' outside of the loop, wont work.

Clueless86
Junior Poster in Training
76 posts since Jul 2009
Reputation Points: 10
Solved Threads: 1
 

You should really check out the tutorial on python.org. Anyway, since you're having trouble wrapping your head around try except, here's a basic outline that handles bad choice slightly differently

#a simple class for our user
class Player:
    def __init__(self,name):
        self.day = 0
        self.name = name
    def __str__(self):
        s = "Player: %s" %(name)
        return s

#get the name of the user
player = Player(raw_input('Name: '))

#for pretty formatting, an easy way to separate menus
def bar():
    s = "-" * 40
    return s

#the main menu, note that it returns a string rather than print it
def menu(player):
    s = """Welcome %s - Day %d!
%s
(1) Store
(2) Home
(3) Advance Day
(0) Quit
%s""" %(player.name,player.day,bar(),bar())
    return s

#same deal as the menu, but this is the store
def store():
    s = """Store
%s
(1) Milk
(2) Eggs
%s""" %(bar(),bar())
    return s

#another menu type thing, but it's home
def home(player):
    s = """%s's home
%s""" %(player.name,bar())

#endless game loop
while 1:
    #whenever it loops, it will begin with the menu
    print menu(player)
    #note that we get raw_input
    choice = raw_input("Choice: ")
    print bar()
    if choice == '1': #choice will always be a string!
        print store() #note that we print the function call
        enter = raw_input("<press enter to cont>")
        print bar()
    elif choice == '2':
        print home(player) #pass the player object to the function
        enter = raw_input("<press enter to cont>")
        print bar()
    elif choice == '3':
        print "Advancing a day..."
        player.day = player.day + 1 #modify the player object
    elif choice == '0':
        print "Quitting" #tell them you're quitting...
        break #and then break out of the loop
    else: #if choice is not equal to a menu option, handle it gracefully
        print "Invalid Choice"
        print bar()


#any code below me will execute after player "quits"
zachabesh
Junior Poster
106 posts since Jun 2008
Reputation Points: 16
Solved Threads: 17
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You