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.