H
H
hokim2014-01-09 23:30:04
Python
hokim, 2014-01-09 23:30:04

How to find error in my script (python)?

Hello! I have been studying Python for about a month and my impressions are very good. I wanted to consolidate what I had learned with practice and came up with different tasks for myself. For today, I wanted to make a program that determines a prime or complex number. Basically, the code looks like this:

def Simple(n):
    h=2
    while n > h:   
        if n%h != 0:
            itog = "True"
            
        else:
            itog = "False"
            break
        h = h+1
    if itog == "True":
        print ("{0} - Простое число".format(n))
    else:
        print("{0} - Сложное число".format(n))
n = int(input("Введите число:\n"))
while n > 1:
    Simple(n)
    n = n - 1

The program works, but at the end it says:
Traceback (most recent call last):
File "C:\Python33\ex\simple_2.py", line 18, in
Simple(n)
File "C:\Python33\ex\simple_2.py ", line 12, in Simple
if itog == "True":
UnboundLocalError: local variable 'itog' referenced before
assignment

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
mysticmirage, 2014-01-10
@rhino_o

In your Simple procedure, for n <= h, the while loop is not executed. Therefore, the variable itog is not defined. I won't discuss your algorithm for finding primes, but try setting itog to False before the loop. Something like this:

def Simple(n):
    h=2
    itog = False
    while n > h:   
        if n%h != 0:
            itog = True
        else:
            break
        h = h+1
    if itog == "True":
        print ("{0} - Простое число".format(n))
    else:
        print("{0} - Сложное число".format(n))
n = int(input("Введите число:\n"))
while n > 1:
    Simple(n)
    n = n - 1

PS As already mentioned above, instead of strings, you need to use True / False without quotes.
PPS A couple more notes:
1. If the type of the variable is boolean, then you can
just use
2 instead. Usually, functions (procedures) in Python are written with a lowercase letter (under_score-notation). With a capital (CamelCase) it is customary to name classes.

K
Konstantin Dovnar, 2014-01-10
@SolidlSnake

I don't understand, why are you using strings instead of booleans?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question