Search code examples
pythonloopsiterationincrement

Python incrementally set a variable to equal another variable


I am attempting to set the value of a variable to incrementally equal that of another variable based on the iteration of the loop I am on.

I have the following code:

no_keywords=3

cat_0='Alpha'
cat_1='Bravo'
cat_2='Charlie'
cat_3='Delta'

for _ in range(no_keywords):

  keyword1 = exec(f'cat_{_}')
  
  print(keyword1) 

However the printed value just returns a NoneType object. I would like the value of Keyword1 to take on the value of the cat_ variable based on the iteration of loop I am on.

Please can somebody help in explaining in what I am doing wrong and help me recitfy?

Thanks,

D


Solution

  • Try this:

    no_keywords = 3
    
    cat_0 = 'Alpha'
    cat_1 = 'Bravo'
    cat_2 = 'Charlie'
    cat_3 = 'Delta'
    
    for _ in range(no_keywords):
        keyword1 = None
    
        exec(f'keyword1 = cat_{_}')
    
        print(keyword1)
    

    Seems like exec does not return a value, but you can set your variable within the command passed to it.