如何在函数内编辑全局变量?

问题描述 投票:-1回答:1

我正在尝试编辑函数中的某些全局变量,但是即使使用了global关键字,全局变量也不会更改。

我曾尝试使用全局词,但不起作用。我还尝试过在函数之后初始化变量,但似乎没有什么区别

def Knight():
    global Class
    Class = "Knight"
    global Health
    Health = 150
    global Mana
    Mana = 100
    global damageMult
    damageMult = 1
    global spellMult
    spellMult = 1
    global Weapons
    Weapons.append(0)
    global Location
    Location = 0
    return

def selectClass():
    classChoice = input("""Choose your Class...
1. Knight
2. Warrior
3. Archer
4. Thief
5. Mage
Select: """)
    if classChoice == 1:
        Knight()
    elif classChoice == 2:
        Warrior()
    elif classChoice == 3:
        Archer()
    elif classChoice == 4:
        Theif()
    elif classChoice == 5:
        Mage()
    return


def newGame():
    selectClass()
    global Class
    print(Class)



def continueGame():
    print("Hello")


def resetGame():    #delete save file
    print("Hello")

Health = 0
Mana = 0
damageMult = float(0)
spellMult = float(0)  #for spell damage, set to low damage so only effective for mage
Class = ""
Weapons = []
Location = 0

newGame()

我希望newGame函数在选择该选项后会打印“ Knight”,但它什么都不做

python variables global
1个回答
0
投票

[Knight永远不会被调用,因为您正在将input()返回的字符串与int 1进行比较。

def selectClass():
    classChoice = input("""Choose your Class...
1. Knight
2. Warrior
3. Archer
4. Thief
5. Mage
Select: """)
    if classChoice == "1":
        Knight()
    elif classChoice == "2":
        Warrior()
    elif classChoice == "3":
        Archer()
    elif classChoice == "4":
        Theif()
    elif classChoice == "5":
        Mage()
    return
© www.soinside.com 2019 - 2024. All rights reserved.