如何在if语句中将局部变量转换为全局变量

时间:2018-05-20 15:16:00

标签: python

async def purchase(ctx, weapon, quantity):
    if weapon == "0":
        weapon_name = "soldier#"
    elif weapon == "1":
        weapon_name = "sniper#"
    elif weapon == "2":
        weapon_name = "demolitionist#"
    elif weapon == "3":
        weapon_name = "spy#"
    elif weapon == "4":
        weapon_name = "armored_vehicles#"
    elif weapon == "5":
        weapon_name = "tank#"
    elif weapon == "6":
        weapon_name = "transport_truck#"
    elif profileData["rank"] >= "30":
        if weapon == "7":
            weapon_name = "nuclear_missile#"
        elif profileData["rank"] >= "50":
            if weapon == "8":
                weapon_name = "thermonuclear_missile#"

所以基本上如果他们为参数输入的武器id它等于soldier#这样的字符串,它会影响他们有多少士兵。我只想知道如何将其转换为全局变量

1 个答案:

答案 0 :(得分:0)

您必须在if Statements

中使用之前声明变量
async def purchase(ctx, weapon, quantity):
    weapon_name = ""  # <= just add this ligne
    if weapon == "0":
        weapon_name = "soldier#"
    elif weapon == "1":
        weapon_name = "sniper#"
    elif weapon == "2":
        weapon_name = "demolitionist#"
    elif weapon == "3":
        weapon_name = "spy#"
    elif weapon == "4":
        weapon_name = "armored_vehicles#"
    elif weapon == "5":
        weapon_name = "tank#"
    elif weapon == "6":
        weapon_name = "transport_truck#"
    elif profileData["rank"] >= "30":
        if weapon == "7":
            weapon_name = "nuclear_missile#"
        elif profileData["rank"] >= "50":
            if weapon == "8":
                weapon_name = "thermonuclear_missile#"