I am working on an application to save and analyze my cryptocurrency data. I use 2 different apps, hotbit and binance. Since I have bought, for example, BTC on both hotbit and binance, I want to add HB to the end of BTC to specify that it needs to go into the hotbit table I've created. It should look like 'BTCHB'.
def which_application(self):
print("Which application was this transaction made on? Type either 'hotbit' or 'binance'")
which_application_prompt = input("").strip().lower()
if which_application_prompt == 'hotbit':
self = self 'HB'
return(self)
elif which_application_prompt == 'binance':
pass
else:
print("Invalid input.")
which_application(self)
I've created this function and everything works smoothly inside the function. However, when I call the function and add a value in place of self, it doesn't add HB to it. Any ideas?
CodePudding user response:
You are missing reassigning the value to self
in your recursive call, a fixed version could be:
def which_application(self):
print("Which application was this transaction made on? Type either 'hotbit' or 'binance'")
which_application_prompt = input("").strip().lower()
if which_application_prompt == 'hotbit':
self = self 'HB'
return(self)
elif which_application_prompt == 'binance':
return self
else:
print("Invalid input.")
self = which_application(self)
return self
Works:
$ python3 demo.py
Which application was this transaction made on? Type either 'hotbit' or 'binance'
hotbit
testHB
If you call which_application
again in the else statement a possibly returned value is lost as you do not assign it to self.
Another flaw is when you type binance
nothing is returned - None to be exact.
$ python3 demo.py
Which application was this transaction made on? Type either 'hotbit' or 'binance'
binance
None
Last, a while loop is better than a recursion. Loop until a return.
CodePudding user response:
When you recurse (call the function from within itself), you're also "recreating" its locals, so self
is no longer referring to the same object as self
in the parent call.
Use a loop instead of recursion (and consider using a less confusing parameter name than self
):
def which_application(transaction):
while True:
print("Which application was this transaction made on? Type either 'hotbit' or 'binance'")
which_application_prompt = input("").strip().lower()
if which_application_prompt == 'hotbit':
transaction = transaction 'HB'
return(transaction)
elif which_application_prompt == 'binance':
break
else:
print("Invalid input.")
# since we're neither `break`'ing nor `return`'ing from here,
# the loop will start over