如果在Python中的语句

时间:2012-03-14 00:04:55

标签: python if-statement

好吧,这应该是一个相对容易的。当我运行程序时,我注意到Damage整数没有传递给Damage_Applied if语句。它会在Damage_Applied整数之前正常工作。如何将Damage整数下载到第二个if语句,还是应该重写整个部分?

elif menu_option == 2: 
    print "Damage Taken?"
    Damage = int(raw_input(prompt))
    print "Where would you like damage to be applied?"
    print "1. HP"
    print "2. CP"
    print "3. Armor"

    Damage_Applied = int(raw_input(prompt))

    if Damage_Applied == 1:
        HP = HP - Damage
    elif Damage_Applied == 2:
        CP = CP - Damage
    elif Damage_Applied == 3:
        Armor = Armor - Damage

1 个答案:

答案 0 :(得分:0)

您需要定义: -

  • HP
  • CP
  • 护甲

在Python中,要从另一个值中减去一个值,您需要同时拥有这两个值。目前,在您的代码中,HP = None,这不是数值,因此HP需要定义为数值(这同样适用于CP和Armor),因此我们将其定义为100,如下所示: -

HP = 100

而且,我们还需要使用CP和Armor这样做,所以,像这样: -

CP = 100
Armor = 100

显然,您可以将100s更改为您喜欢的任何内容,它仍然有效。

完整的代码看起来像这样: -

Python 3.x

elif menu_option == 2:
    HP= 100 #Defining 'HP'
    CP = 100 #Defining 'CP'
    Armor = 100 #Defining 'Armor'
    #For future reference, make sure ALL variables used in an 
    #if statement are defined before using them

    print("Damage Taken?")
    Damage = int(input(prompt))
    print("Where would you like damage to be applied?")
    print("1. HP")
    print("2. CP")
    print("3. Armor")

    Damage_Applied = int(input(prompt))

    if Damage_Applied == 1:
        HP = HP - Damage
    elif Damage_Applied == 2:
        CP = CP - Damage
    elif Damage_Applied == 3:
        Armor = Armor - Damage

Python 2.x

elif menu_option == 2:
    HP= 100 #Defining 'HP'
    CP = 100 #Defining 'CP'
    Armor = 100 #Defining 'Armor'
    #For future reference, make sure ALL variables used in an 
    #if statement are defined before using them

    print "Damage Taken?"
    Damage = int(raw_input(prompt))
    print "Where would you like damage to be applied?"
    print "1. HP"
    print "2. CP"
    print "3. Armor"

    Damage_Applied = int(raw_input(prompt))

    if Damage_Applied == 1:
        HP = HP - Damage
    elif Damage_Applied == 2:
        CP = CP - Damage
    elif Damage_Applied == 3:
        Armor = Armor - Damage

该代码应该有效。如果您需要任何帮助,请直接通过' aaron@dibdibguy.com'与我联系;

享受您的新代码!