繁体   English   中英

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

[英]Python 2.6, global variable wont change, calling functions in another function

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())。 它也不会将我返回到函数选项()。 任何帮助非常感谢,谢谢。

没有必要继续在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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM