Question

def coins():
    #randomly generated amount of coins, can throw them
    global num_coins
    print 'You have', num_coins, 'coins left.'
    opt = yon('You could throw a coin if you wanted too. Y/N')
    if opt == 'Y' and num_coins >0 :
        print 'You throw a coin. It clutters around the ground.'
        num_coins = int(num_coins)
        num_coins -= 1
        num_coins = str(num_coins)
        print 'You have', num_coins, 'coins left.'   
    else:
        'You decide to keep your change for later.'
    if num_coins == 1:
        inventory['coins'] = inventory['coin']
    if num_coins == 0:
        del inventory['coin']                               
    return num_coins
    return options()

amount = random.randrange(5, 12)
num_coins = str(amount)
inventory = ['Lighter', 'Phone', num_coins + ' Coins', 'Empty', 'Empty']

Hello all, making a text based game. and I am having a hell of a time trying to get my code to work. When I call the function coins(), and choose to throw a coin. It does not take away any coins from the global variable num_coins. I have a separate function that calls all the functions I have in my code as well, (options()). It also will not return me to the function options(). Any help much appreciated, thanks.

Était-ce utile?

La solution

There is no need to keep switching between int and str. You can use str.format to include the value in a string:

print "You have {0} coins left.".format(num_coins)

Instead of using a global, make num_coins an argument and return it afterwards:

def coins(num_coins):
    ... 
    return num_coins

Now when you call coins, do:

num_coins = coins(num_coins)

It is now much clearer what is happening.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top