您好,我无法从函数中拉出变量,然后在数学方程中使用它。 我可以使用函数usdExRateRand没有问题,但是当尝试从嵌套if语句中的函数使用usdExRate值时,它只使用初始usdExRateRand而不是来自while循环中新定义的函数,我该如何解决这个问题?在while循环中拉出一个变量,并在if语句中嵌套if语句
import random
def whiles():
cur1 = "NZD"
cur2 = "USD"
usdExRate = round(random.random() * (0.909 - 0.101) + 0.101, 3)
print ("usdExRate Initial = $", usdExRate)
nzdExRate = round(random.random() * (1.909 - 1.101) + 1.101, 3)
print ("nzdExRate Initital = $", nzdExRate)
amt = 1000
amt2 = 0
amtPrev = 0
amt2Prev = 0
def usdExRateRand():
usdExRate = round(random.random() * (0.909 - 0.750) + 0.750, 3)
print ("USD Ex Rate = $", usdExRate,"\n")
usdExRateRand()
def nzdExRateRand():
nzdExRate = round(random.random() * (1.505 - 1.101) + 1.101, 3)
print ("NZD Ex Rate = $", nzdExRate, "\n")
nzdExRateRand()
while amt > 0:
def trade1():
# usdExRate = round(random.random() * (0.909 - 0.101) + 0.101, 3)
print ("TRADE 1")
usdExRateRand()
if usdExRate > 0:
# def trade1():
# usdExRate = round(random.random() * (0.909 - 0.101) + 0.101, 3)
# print (usdExRate)
if (usdExRate * amt > amt2Prev):
print ("My Amount to trade =", cur1," $", amt)
print ("my ",cur2,"rate = $", usdExRate)
trd1 = amt * usdExRate
print ("trade1", cur1,"$", amt," * ",cur2,"$",usdExRate," = $", trd1, "\n")
amt2 = trd1
amtPrev = amt
else:
print ("error reluts in a loss\n")
trade1()
trade1()
def trade2():
print ("TRADE 2")
nzdExRateRand()
if nzdExRate > 0:
if (nzdExRate * amt2 > amtPrev):
print ("My Amount to trade =", cur2," $",amt2,"\n")
print ("my", cur1, "rate = $", nzdExRate)
trd2 = amt2 * nzdExRate
print ("trade2", cur2,"$", amt2," * ",cur1,"$",nzdExRate," = $", trd2, "\n")
amt1 = trd2
amt2Prev = amt2
else:
print ("error results in a loss\n")
trade2()
# amtPrev = amt
# def usdExRateom2():
# usdExRate2 = round(random.random() * (1.909 - 1.101) + 1.101, 3)
# print ("my nzd rate", usdExRate2)
#
# if (trd1 * usdExRate2 < amtPrev):
#
# usdExRate2 = round(random.random() * (1.909 - 1.101) + 1.101, 3)
#
# else:
# trd2 = trd1 * usdExRate2
# print ("trade2 =", trd2)
# usdExRateom2()
whiles()
希望我复制了代码工作中Spyder的代码的时候得到了我的压痕正确的这个时候,我得到这个输出后可以看到“我的量交易”美元恩率始终0.3不以上值。
TRADE 1
USD Ex Rate = $ 0.761
My Amount to trade = NZD $ 1000
my USD rate = $ 0.3
trade1 NZD $ 1000 * USD $ 0.3 = $ 300.0
TRADE 2
NZD Ex Rate = $ 1.178
error results in a loss
TRADE 1
USD Ex Rate = $ 0.772
My Amount to trade = NZD $ 1000
my USD rate = $ 0.3
trade1 NZD $ 1000 * USD $ 0.3 = $ 300.0
TRADE 2
NZD Ex Rate = $ 1.296
我想要做的是。
def trade():
usdExRaterand()
这应该给我一个新的usdExRate变量然后我可以在使用if语句
我打过电话usdExRateRand在实际的if语句和有同样的问题 –
你知道如何从一个函数与'return'语句返回值以及如何传递值的功能呢? 'usdExRateRand'函数应该返回'usdExRate',然后你可以将这个值赋给while循环中的'usdExRate'变量。 ---你的程序是以一种奇怪的方式构建的,我建议首先将所有函数定义从'whiles'函数中移出。在其他函数中嵌套函数可能很有用,但初学者不应该这样做。 – skrx
[Here's](http://programarcadegames.com/index.php?chapter=functions&lang=de#section_9)一个很好的函数介绍。 – skrx