+ 1
How do you assign a variable a new value and keep returning it until it changes?
def trend(value): trend = 0 if value ==3: trend ='bull' return trend if value == 5: trend = 'bear' return trend for value in range(10): print(trend(value))
8 ответов
+ 2
Reuben Hawley
Check the generator code.
trend = 0
def trend():
global trend
trend = 0
for value in range(10):
if value == 5:
trend = 'bear'
if value == 3:
trend ='bull'
yield trend
for i in trend():
print(i)
+ 1
Théophile that works. Great thanks. If it isnt too much to ask, all good and well having the answer but id like to understand why. If you could explain it or point me to a reference that does, it would be greatly appreciated
+ 1
When you define a function like that :
def func(a = []) :
pass
a is always the same object, each time you call it. It only works with types like lists, dictionnaires, etc... (it doesn't work with basic types : int, float,...).
So, in our example, if you modify the list a inside 'func', then because a is always refering to the same object, the 'changes' on a are saved.
I don't really know how to explain better.
0
Try this:-
def trend(value):
default = 0
if value ==3:
return 'bull'
if value == 5:
return 'bear'
return default
for value in range(10):
print(trend(value))
0
Look at that :
It isn't really a variable, but an object of type list. It can fit the job!
https://code.sololearn.com/cYtVK9q4L6lt/?ref=app
0
I think this is what you want.
for value in range(10):
result = trend(value)
if result is not None:
print(result)
0
o.gak this returns the value if a none value is not true but doesnt carry over the value from its last assignment
0
Thanks that makes sense since the lists values are always stored in memory. Is it possible to achieve the same result in this code with a generator?