简体   繁体   中英

assigning variable prior to elif statement

this might be very basic but I am not getting any clue

my code is something like this:

for tickers in ticklist:
  if function_1(x,y) is True:
     do task1
  elif function_2(x,y) is True:
     do task1
  elif function_3(x,y) > a and function_3(x,y) < b:
     do task1
  else:
     do task2

I know that this code is equivalent to having:

for tickers in ticklist:
  if function_1(x,y) is True or function_2(x,y) is True or function_3(x,y) > a and 
  function_3(x,y) < b:
     do task1
  else:
     do task2

The reason for breaking into multiple lines is to prevent the unwanted condition check and save loop time because each function here represents an api call (which takes quite a bit of time). So, my goal is to end the loop once one condition is True. However, in the third condition the same function is called twice (which means calling api twice).

...
elif function_3(x,y) > a and function_3(x,y) < b:
     do task1

Is there a way to assign the return of a function to a variable before entering into elif so that the condition can be checked with the assigned variable rather than going to the function twice.

something like:

...
elif var = function_3(x,y) 
    if var> a and var < b:
     do task1

I think something like:

if func_1(x,y):
  Task 1
elif func_2(x,y):
  Task 1
else:
  n = func_3(x,y)
  if n>a and n<b:
    Task 1
  else:
    Task 2

would work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM