0

I have a function within which I have a for loop that is looking for a certain string, which if true executes a different function. What I can't work out is how to create a variable within which to store the outcome of the for loop. I want to take the outcome (i.e. this function was executed or this string was present) and pass that into another function but I cannot get the variable to remember the outcome. Any help would be greatly greatly appreciated. Thank you

for something in something:
    def a_func():
        
        if this  == 'A':
            func_1()
        if this  == 'B':
            func_2()    
        if this  == 'C':
            func_3()  
        if this  == 'D':
            func_4() 

        return this

    this = a_func()
  • 1
    `return func_1()`? – Sayse Apr 30 '22 at 21:49
  • @Sayse I tried returning the function name to no success – Doodling Apr 30 '22 at 21:54
  • the function name? you need to return the function you call – Sayse Apr 30 '22 at 22:10
  • As mentioned by @Sayse you could simply add `return` to each of your func_1 to func_4 calls, however based on the code, if your func_1 to func_4 do not return A, B, C or D, then I dont see this code being useful after the first iteration. – SShah Apr 30 '22 at 22:12
  • @SShah thanks for your input, you're right it's only useful for one iteration as I know one of the four options will definitely be present and I want to take it's value and do something different the next time the for loop iterates. Do you have any advice for doing that? – Doodling Apr 30 '22 at 22:33
  • @Doodling that sounds confusing sorry, if its useful only for the first iteration, then I highly recommend you use sarthakt's solution below, and then do what you do on the first iteration independantly outside of the loop. From this you will first identify what specific function to call first and then only after would you need to trigger a loop where you process everything after your first iteration.. I hope that makes sense. – SShah Apr 30 '22 at 22:46
  • @SShah No not at all, I'm very new to python and coding in general so I understand I lack the ability to communicate what I'm trying to achieve. I have implemented sarthakt's solution and realise it is much better for the function definitions to be outside of the for loop and to only call the for loop once my ducks are in a row. What I'm having trouble with now is getting the value from the first iteration and passing it to the next to trigger a different function – Doodling Apr 30 '22 at 22:55
  • @Doodling I understand your new to coding so for your current request I recommend you to understand how variables work first and look up global and local scoping for variable declaration. 1 solution for what you asked would be to have a variable defined possibly on the Global scope (in this case outside of your loop) and then within the loop you can update the variable value, which future iterations can use the updated value to do something else. My recomendation is similar to MaLiN2223's answer from here: https://stackoverflow.com/questions/42040868/how-to-add-a-counter-to-a-while-loop – SShah May 01 '22 at 00:07

2 Answers2

1

What you want to do and what you have done do not seem to align well. Currently, your code is poorly written. However, it can be fixed as follows:

def func_1():
    return 1
    
def func_2():
    return 2
    
def func_3():
    return 3
    
def func_4():
    return 4
    
action_for_value = {
    'A': func_1,
    'B': func_2,
    'C': func_3,
    'D': func_4,
}
    
for something in ['A', 'B', 'C', 'D', 'E']:
    print(action_for_value[something]() if something in action_for_value else "Not found!!")

This example stores functions corresponding to values in a dictionary and then basis if the value is present, makes a function call.

Here it is in action.

Some notes about your current code:

  1. Declaring a function inside a for loop is never correct, and has quite a few consequences. Move it outside the for block, and then call the function inside the for block.
  2. You want to assign the value of the func_x to a variable which is either global or at least outside the for loop. Alternatively, you can return from a_func the value from func_x as if this == 'A': return func_1() and then use the return value to assign this.

From the looks of it, I would ask you to review your understanding of the basics of Python. A lot of it seems cobbled together without a good understanding of what is happening.

sarthakt
  • 42
  • 1
  • 7
  • 1
    This response is quite aggressively worded. It might be helpful to soften the tone. – autopoietic Apr 30 '22 at 22:11
  • This worked and I learned a lot thank you so much. What if say, 'A' was the only string present in 'something' and I wanted to pass it's corresponding function onto another function. Would I use the 'A' function as a parameter in the next function? – Doodling Apr 30 '22 at 22:30
  • "You want to assign the value of the func_x to a variable which is either global or at least outside the for loop. Alternatively, you can return from a_func the value from func_x as if this == 'A': return func_1() and then use the return value to assign this." - How do I do this in the if statement? would it look like if this == 'A': return func_1() this = func_x() ? "From the looks of it, I would ask you to review your understanding of the basics of Python.." - 100% you're correct, I'm doing my best to learn and understand python basics. I appreciate your input immensely – Doodling Apr 30 '22 at 23:07
  • 1
    @autopoietic point taken. will be better with my future answers :) – sarthakt May 02 '22 at 10:22
  • @Doodling, for > What if say, 'A' was the only string present in 'something' and I wanted to pass it's corresponding function onto another function. Would I use the 'A' function as a parameter in the next function? you could just pass it as `some_func(action_for_value['A'])` and then in `some_func` body, you could say `def some_func(func_for_A): func_for_A()`. – sarthakt May 02 '22 at 10:24
0

I'm not sure what you're actually trying to do, but defining a function inside of a for loop is definitely not the way to do so.

def func_1():
    pass

def func_2():
    pass

def func_3():
    pass

def func_4():
    pass

def a_func(this):
    if this  == 'A':
        func_1()
        return f'{this} found and func_1() ran.'
    elif this  == 'B':
        func_2()    
        return f'{this} found and func_2() ran.'
    elif this  == 'C':
        func_3()  
        return f'{this} found and func_3() ran.'
    elif this  == 'D':
        func_4() 
        return f'{this} found and func_4() ran.'
    else:
        pass
        

something = ['A', 'B', 'C', 'D']

outputs = [a_func(x) for x in something]

for value in outputs:
    print(value)

Output:

A found and func_1() ran.
B found and func_2() ran.
C found and func_3() ran.
D found and func_4() ran.
BeRT2me
  • 12,699
  • 2
  • 13
  • 31