How do you assign a variable a new value and keep returning it until it changes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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))

5th Nov 2019, 6:44 PM
Reuben Hawley
Reuben Hawley - avatar
8 Answers
+ 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)
9th Nov 2019, 7:44 AM
o.gak
o.gak - avatar
+ 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
7th Nov 2019, 9:49 AM
Reuben Hawley
Reuben Hawley - avatar
+ 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.
7th Nov 2019, 11:58 AM
Théophile
Théophile - avatar
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))
5th Nov 2019, 6:58 PM
rodwynnejones
rodwynnejones - avatar
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
5th Nov 2019, 8:06 PM
Théophile
Théophile - avatar
0
I think this is what you want. for value in range(10): result = trend(value) if result is not None: print(result)
5th Nov 2019, 9:11 PM
o.gak
o.gak - avatar
0
o.gak this returns the value if a none value is not true but doesnt carry over the value from its last assignment
7th Nov 2019, 9:47 AM
Reuben Hawley
Reuben Hawley - avatar
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?
8th Nov 2019, 8:04 PM
Reuben Hawley
Reuben Hawley - avatar