我正在尝试使第一个功能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]()
答案 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):