Posts: 4,559
Threads: 1,464
Joined: Sep 2016
suppose i have a bunch of code like
if first_name == 'alex':
return 1
if middle_name == 'larry':
return 2
if middle_name == 'mark':
return 3
if first_name == 'sarah':
return 4
if surname == 'smith':
return 5
duplicated in several places and i want to reduce the duplication by putting it in a function. how would i do that?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,559
Threads: 1,464
Joined: Sep 2016
(Mar-06-2021, 05:13 AM)michael1789 Wrote: Python dictionary.
dict = {'alex' : 1,
'larry' : 2,
'mark' : 3}
print(dict['mark'])
the example i gave involves testing various different variables. maybe it's a bad example. the "bunch of code" can't be changed. the question is about how to have function A call function B and have function B effect the return all the way to the caller of function A. put the "bunch of code" inside function B so function A can just call function B in all those places it had that "bunch of code". but what about those returns? can function B do a return for function A? not really. see the complication?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,559
Threads: 1,464
Joined: Sep 2016
what if the "bunch of code" only returns in some cases and "falls through" in others?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Posts: 4,559
Threads: 1,464
Joined: Sep 2016
Mar-08-2021, 08:18 AM
(This post was last modified: Mar-08-2021, 08:18 AM by Skaperen.)
so do i get to put the duplicated and complicated decision making code in a function? i'm guessing B() should raise an exception. then A() gets the exception or A()'s caller does.
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.