I’m just starting to learn python and keep getting an error that I just can’t figure out. Any help would be massively appreciated. Basically, I keep getting the following error:
Enter an int: 8
Traceback (most recent call last):
File "C:\Users\Samuel\Documents\Python Stuff\Find Prime Factors of Number.py", line 16, in <module>
once_cycle()
File "C:\Users\Samuel\Documents\Python Stuff\Find Prime Factors of Number.py", line 8, in once_cycle
while x==0:
UnboundLocalError: local variable 'x' referenced before assignment
I see lots of people are having the same problem, but when I look at what people have told them to do I can’t figure it out. Anyway, my code is this. I’ve re-checked all my indentation and can’t see a problem with it. The aim of this program is to find the prime factors of an int (although it’s only 90% complete). It’s written in Python 2.7.3.
import math
testedInt = float(raw_input("Enter an int: "))
workingInt = testedInt
x = 0
def once_cycle():
for dividor in range(1, int(math.floor(math.sqrt(testedInt))+1)):
while x==0:
print "Called"
if (workingInt%dividor == 0):
workingInt = workingInt/dividor
x = 1
if (workingInt > 1):
once_cycle()
return
once_cycle()
print workingInt
Thanks in advance for any help,
Sam
In your
one_cycle()function you are at some point assigning tox:This makes
xa local variable. You are also referring to it with a test:but before it is assigned to. This is the cause of your exception.
Either add
x = 0at the start of your function, or declare it a global (if that is what you meant it to be). By the looks of it, you don’t usexoutside of the function, so you probably didn’t mean it to be.The following works;
workingIntis also being modified so it needs to be declaredglobal:or, simplified:
int(floating_point_number)already takes the floor of a floating point argument.Note that you end up with an infinite loop if
workingInt % dividoris not0. The first timetestedIntis an odd number, this is going to hit you, for example, and your loop will never exit.Take
11, for example; you’ll try the divisors1,2, and3. While1is a divisor,workingIntwill remain11and the loop breaks. Nextforloop, the divisor is2, andworkingInt % 2is not ever going to give you0, so the loop will continue forever.