函数中的积分变量不起作用

时间:2018-09-12 12:52:06

标签: python python-3.x

我正在尝试使第一个功能opt1()使健康降低50点,但是由于某种原因它不起作用。代码不在函数中时起作用。 无效的行:health = int(health) - 50

import random


health = "100"
p = "1"


def opt1():
   print("Du förlorade striden")
   health = int(health) - 50
   print(health)


def opt2():
   print("hej2")


def opt3():
   print("hej3")


q = [opt1, opt2, opt3]
ind = random.randint(0,len(q)-1)


print("you have ", p, " potions")
print("Your health is ", health,)
while True:
   print("Commands: Add, drink, sleep, fight, quest")
   a = input("Enter a command: ")
   if a == "add":
       health = int(health)
       p = int(p) + 1
       print("you have ", p, " potions")
       print("Your health is ", health,)
   if a == "fight":
       q[ind]()

2 个答案:

答案 0 :(得分:0)

因此我将health变量更改为一个整数。

并将global添加到函数中:

import random

health = 100
p = "1"


def opt1():
    global health
    print("Du förlorade striden")
    health -= 50
    print(health)


def opt2():
    print("hej2")


def opt3():
    print("hej3")


q = [opt1, opt2, opt3]
ind = random.randint(0,len(q)-1)


print("you have ", p, " potions")
print("Your health is ", health,)
while True:
    print("Commands: Add, drink, sleep, fight, quest")
    a = input("Enter a command: ")
    if a == "add":
        health = int(health)
        p = int(p) + 1
        print("you have ", p, " potions")
        print("Your health is ", health,)
    if a == "fight":
        q[ind]()

此外,您可以在Python here中的scoping上阅读更多内容。

希望这对您有帮助!

答案 1 :(得分:-1)

def opt1():

在opt1中,您应该声明要提供给函数的变量。

例如:

def opt1(health):