function_name未定义错误

时间:2017-06-02 20:11:36

标签: python-3.x runtime-error

我想在python中编写一个函数,告诉我给出的数字是否为素数,到目前为止,我的代码是:

def enter_input():
    n=input("Enter the number to be checked\n")
    return n

def check():
    o=int(enter_input())
    r=o
    print(type(o))
    print(type(r))
    bool=True
    for i in range(2,r,1):
        if(o%i==0):
            return False
    return True

def display():
    print("Entered Number Is {0}".format(p))
    print("The Number is a Prime:{0}".format(check()))


enter_input()
check()
display()

但输入数字后我得到了这个错误:

运行: -

Enter the number to be checked
23
Traceback (most recent call last):
    File "Chech_Prime.py", line 8, in check
    o=int(enter_input())
    NameError: name 'enter_input' is not defined

Repl已关闭

我哪里出错了?这是我第一次尝试函数调用,看起来我调用enter_input()函数的地方找不到它。谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

你写的东西有点奇怪,所以我会解释为什么这应该做你正在演绎的东西:

这是你的代码,我会在行之间做出评论:

def enter_input():
    n=input("Enter the number to be checked\n")
    return n 

def check(): # you create the check function, and then a display function, and is not necesary, because you want to do both thinks in the same function
    o=int(enter_input()) # you call this function a lot of times, and you only want to input the value once, so, is better to call the input method inside the function
    r=o # is better to name variables more descriptive, I mean, check() as a function, what checks? maybe you want to call it is_prime(), more descriptive, o and p... doesn't say anything, but input sounds better
    print(type(o))
    print(type(r)) #this auxiliar variable is not needed
    bool=True
    for i in range(2,r,1):
        if(o%i==0):
            return False
    return True

def display():
    print("Entered Number Is {0}".format(p))
    print("The Number is a Prime:{0}".format(check()))# here you again call the function, and again it ask to you to add a input... not good


enter_input()
check() # and again.. three times, that's so confusing even to follow when you are adding the inputs
display()

我的方法是:

def print_is_prime():
    value_to_eval=int(input("Enter the number to be checked\n"))

    print("the type of the value is " + str(value_to_eval.__class__.__name__))

    is_prime =True #initial value is correct
    for i in range(2,value_to_eval,1):
        if(value_to_eval%i==0):
            is_prime = False #here, you detect is not prime
            break # so with break you can avoid to execute innecesary all the loop

    is_prime = True and is_prime # with and operator, true is the neutral, so the value will be always the other value, in this case, is_prime, this like 0 + x, the value will be always x

    print("Entered Number Is {0}".format(value_to_eval))
    print("The Number is a Prime:{0}".format(is_prime))

print_is_prime()