簡體   English   中英

def函數python 3.4.0內部的變量重置

[英]variable resets inside of def function python 3.4.0

我只是在一兩個星期前才開始編碼,所以我仍然不了解很多基礎知識,但本質上發生的是,每當函數重新啟動時,我的“ money”變量會重置為十,如果我將變量放在外面,則會出現錯誤,說“在分配之前已引用了金錢”我嘗試了其他選項,例如全局語句,該問題仍然存在。

def main():

    money = 10.00
    print('Welcome to the vending machine.')




    print('The snacks available are:')
    print('1. Chips - $2.50')
    print('2. Chocolate Bar - $3.00')
    print('3. Water - $1.90')
    print('4. Cookie - $0.85')
    print('5. Skittles - $2.00')
    print('6. Pringles - $4.00')
    print('7. Exit')
    print('You have',money,'remaining!')

    a = input('What would you like to purchase?')
    if a == '1':
        money = money - 2.5 
        print('You have bought chips for $2.50 you have $',money,'remaining!')

    if a == '2':
        money = money - 3
        print('You have bought a chocolate bar for $3.00 and have $',money,'remaining!')

    if a == '3':
        money = money - 1.90
        print('You have bought water for $1.90 and have $',money,'remaining!')

    if a == '4':
        money = money - 0.85
        print('You have bought a cookie for $0.85 and have $',money,'remaining!')

    if a == '5':
        money = money - 2.00
        print('You habe bought skittles for $2.00 and have $',money,'remaining!')

    if a == '6':
        money = money - 4.00
        print('You have bought pringles for $4.00 and have $',money, 'remaining!')

    c = input('Would you like to make another purchase? Y/N').upper()
    if c == 'Y':
        main()
    if c == 'N':
        exit
    else:
        exit


main()

您在def main()的開頭設置money = 10如果再次調用它,它將被重置為它,因為它是main方法范圍內的局部變量。

您可以在外部定義它並將其提供為參數:

def main(money):
    # no money def here, it is provided as parameter

    # your code

    if c == 'Y':
        main(money) # pass the remainder money on
    else:
        exit()

main(10) # call the main() with your initial money

更好的方法是讀取循環並在while循環中處理循環, while不是一次又一次地遞歸到main(...)


使用while的版本,商品/價格的查詢字典,一些循環和檢查:

def menu(items, money):
    print('The snacks available are:')

    for key,value in sorted(items):
        if value[1]:
          print(f"{key}. {value[0]} - ${value[1]}")
        else:
            print(f"{key}. {value[0]}")

    print(f'You have ${money} remaining!')

# your wares
ex = "Exit"    
what = {'1': ('Chips', 2.5),        '2': ('Chocolate Bar', 3),
        '3': ('Water', 1.9),        '4': ('Cookie', 0.85),
        '5': ('Skittles', 2),     '6': ('Pringles', 4),
        '7': (ex, None)}

def main(money = 10.0):
    menu(what.items(), money)
    while True:
        a = input('What would you like to purchase? ') 

        # handle bad input
        if a not in what:
            print("Not possible. Try again:")
            # reprint menu
            menu(what.items(), money)
            continue

        if what[a][0] == ex:
            print("Bye.")
            break
        else:
            thing, cost = what[a] 
            if cost < money:
                money -= cost
                print(f'You have bought {thing} for ${cost}. You have $ {money} remaining!')
            else:
                print(f"Too expensive. You have $ {money} remaining!'")

        c = input('Would you like to make another purchase? Y/N ').upper()

        if c == 'N':
            print("Bye.")
            break

main()

輸出:

The snacks available are:
1. Chips - $2.5
2. Chocolate Bar - $3
3. Water - $1.9
4. Cookie - $0.85
5. Skittles - $2
6. Pringles - $4
7. Exit
You have $10.0 remaining!
What would you like to purchase? 1
You have bought Chips for $2.5. You have $ 7.5 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 2
You have bought Chocolate Bar for $3. You have $ 4.5 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 3
You have bought Water for $1.9. You have $ 2.6 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 4
You have bought Cookie for $0.85. You have $ 1.75 remaining!
Would you like to make another purchase? Y/N Y
What would you like to purchase? 5
Too expensive. You have $ 1.75 remaining!'
Would you like to make another purchase? Y/N Y
What would you like to purchase? 6
Too expensive. You have $ 1.75 remaining!'
Would you like to make another purchase? Y/N Y
What would you like to purchase? 7
Bye.

聲明在函數中使用全局變量

money = 10.0

def main():
    global money
    money = 5.0
    # ...

在函數外將變量“ money”定義為全局變量。 像這樣;

money = 10.0

def main():
   global money
   #some stuff 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM