[英]Variables don't change after being run through a function
我正在用python写一个小游戏,其中发生某些事件并影响需要保留在某些参数中的变量。 我有主文件,然后有另一个文件,其中包含所有事件。 在函数中更改了某些值,然后应该更改main中的整体值(对不起,如果没有意义的话)
这是主要部分:
while (army > -100 and army < 100 and people > -100 and people < 100 and church > -100 and church < 100 and affairs > -100 and money < 100 and money > -100):
os.system('clear')
#Top Bar. Should Stay throughout game.
print("[-]==[King: " + king + "]==[Years in power:" + str(years) +"]==[Army: " + str(army) + "]==[People: " + str(people) + "]==[Church: " + str(church) + "]==[Foreign Affairs: " + str(affairs) + "]==[Economy: " + str(money) +"]==[-]")
print(people)
event1(army, people, church, affairs, money, years)
一直循环直到其中一个参数降到0以下才出现丢失情况
现在只有一个事件,还没有完全结束,但是我只需要一件事就至少可以看到值的变化。
在这里:
def event1(army, people, church, affairs, money, years):
#Feilds are Flooding
print("")
print("Sire! The Feilds in the eastern baronies are flooding! What should we do?")
print("")
print("Choices:")
print("1: The rain will pass, do nothing. (~Money, People)")
print("2: Have the Royal Builders build flood protection! (~Money, People)")
print("")
c=input("Your choice sire: ")
while True:
if c > 2:
print("")
print("Please chose a valid option")
print("Your choice sire: ")
continue
if c == 1:
time.sleep(2)
print("")
print("You do nothing, your people starve from flooded feilds (-People, +Money)")
money = money+20
people = people-20
years = years+1
raw_input("Press Enter to go to the next year")
return money
return years
return people
break
事件运行后,人们,金钱和岁月的价值都应该发生变化,但是当它循环时,没有任何变化。
任何帮助表示赞赏! 谢谢!
这些是局部变量。 一旦离开方法范围,该值就会丢失,除非您返回并实际使用返回的值。
在调用方中,为变量分配新的返回值:
money, years, people = event1(army, people, church, affairs, money, years)
在event1
,仅执行包含要返回的3个值的tuple
一个 return
(其他不可达)( 解压缩到3个上层同义变量中):
return money, years, people
您不需要退货!!!!!!!!!!!!!!!!!!!! 完全删除它! 读这个! (应该有帮助)
实际上,该返回会破坏您的命令,并且有一种非常容易解释的方法来理解其工作原理。
首先,我需要解释一些事情,因为我对您的代码有些困惑。 Return用于使您返回的命令值不变。 返回是这样使用的:
def AddThreethousandTwohundredSeventyNineToNum(num):
num = num + 3279
return num
接着
print AddThreethousandTwohundredSeventyNineToNum(4)
它应该打印“ 3283”。 (3279 + 4)
print printThreethousandTwohundredSeventyNineToNum(2)
它将打印“ 3281”。
您还可以做一些很酷的事情,例如:
if AddThreethousandTwohundredSeventyNineToNum(x) == y:
DoSomething
所有的回报就是使函数的值成为您想要的任何值。 在最后的代码中,该函数查找我制作的num
,并看到它是4或2,因此它执行num = num + 3279
,因此num
增加了3279(3273或3271)。 当您return num
,它会使THE FUNCTION等于num
。
这意味着您要做的就是更改了第21-23行中的所有这些美丽值(金钱,人等),而从技术上讲,这就是您要做的一切。 但是,当您返回数字时,您使命令不仅更改了这些值,而且还变成了数字,显然,您不能仅在命令中放一个数字。 否则,口译员将无法理解。
我希望我已经足够清楚了,如果没有,请告诉我(请)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.