[英]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.