Python 2.6,全局变量不会改变,在另一个函数中调用函数

时间:2014-03-11 23:30:30

标签: python function global-variables global python-2.6

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']

大家好,制作基于文字的游戏。我有一段时间试图让我的代码工作。当我调用函数coins()时,选择投掷硬币。它不会从全局变量num_coins中带走任何硬币。我有一个单独的函数,它调用我的代码中的所有函数,(options())。它也不会将我返回到函数选项()。非常感谢任何帮助,谢谢。

1 个答案:

答案 0 :(得分:2)

无需在intstr之间切换。您可以使用str.format将值包含在字符串中:

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

不是使用global,而是使num_coins成为一个参数,然后再return

def coins(num_coins):
    ... 
    return num_coins

现在,当您致电coins时,请执行:

num_coins = coins(num_coins)

现在发生的事情要清楚得多。