Practice makes perfect. weirdness with local variables


#1


https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/5?curriculum_id=4f89dab3d788890003000096

the code i have currently works (even though it is incredibly hacky)

however if i comment out
num = 0
num += x

and uncomment

num == x

i get this error message

UnboundLocalError: local variable 'num' referenced before assignment

im not understanding something about either scope or order of operations in python methods (i think) however due to the fact that i don't know what i'm doing wrong, i don't know how to google around for answers or help


def factorial(x):
    total = 1
    # num == x
    num = 0
    num += x
    for _ in range(x):
        total *= num
        num -= 1
    return total

print factorial(4)


#2

never mind.
num = x solves this.
i dont know why i was trying num == x
i was trying to set a variable equal to x without defining the variable first
i am tired.
sorry for posting this


#3

In truth, you don't need a num variable, at all.

for _ in range(x):
    total *= (1 + _)

Demo

>>> x = 7
>>> total = 1
>>> for _ in range(x):
	total *= (1 + _)

	
>>> total
5040
>>>

#4

so if i'm understanding correctly the _ just represents every number from 0 to (x - 1)
aka 0-6
so you take 1, add it to _, and then *= the total by that number. that way you do
1 *= 1
1 *= 2
2 *= 3
6 *= 4
24 *= 5
120 *= 6
720 *= 7
which would give you that total.
awesome, thanks for the clarification on exactly how that bit of code functions!


#5

Correct. Glad you recognize how it works, in this instance.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.