簡體   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