1

I have the following assignment.

"Create 5 variables named factorN where N is the numbers 1 to 5 and set them 1 through 5 respectively."

Specifically, the assignment looks like this.

def exercise()
    #Create 5 variables named factorN where N is the numbers 1 to 5, 
    #and set them 1 through 5 respectively.

    # ------ Place code below here \/ \/ \/ ------

    # ------ Place code above here /\ /\ /\ ------

    return factor1, factor2, factor3, factor4, factor5

When I run the following code outside of the function, it works fine.

for n in range(1,6):
    name = "factor" + str(n)
    vars()[name] = n

 print(factor1) #prints 1
 print(factor2) #prints 2

But when I try to put this code inside the function like so, and if I haven't run the above function first...

def exercise():
    for n in range(1,6):
        name = "factor" + str(n)
        vars()[name] = n
    return factor1, factor2, factor3, factor4, factor5

exercise()

Then I get the following error:

"NameError: name 'factor1' is not defined."

Does anyone know an alternative to vars()[] that works inside of a function? I do not want the variable factor1 to exist outside of the function.

I already submitted this assignment, but initially I used globals() instead of vars(). This passed the unit test of exercise() returning numbers 1-5, but was marked as incorrect because it created factor1 as a global variable. I understand now the risks of creating global variables inside a function, but I don't know how to get factor1 as a variable to exist inside the function only.

hmgeiger
  • 121
  • 1
  • 4
  • 4
    That's a terrible exercise. There should just be one sequence-valued variable named `factor`. For example, `factor = [1,2,3,4,5]`. – chepner Sep 13 '18 at 19:21
  • python already has an idea of what your variables are in the function. The function is already compiled so basically it is too late. – Jean-François Fabre Sep 13 '18 at 19:22
  • No, that's not how Python works. – Klaus D. Sep 13 '18 at 19:24
  • Yes @chepner, every somewhat related link I found on this question just basically said, "Dynamically creating variable names is a terrible idea." I realize that is the case, but I was still wondering if I could learn how to do this thing that you are not really supposed to do to fulfill the exercise lol. – hmgeiger Sep 14 '18 at 20:48
  • Update: Turns out professor literally just wanted us to make 5 different variables. E.g. factor1 = 1, factor2 = 2, etc. I overthought things. – hmgeiger Sep 16 '18 at 21:20

0 Answers0