2017-06-02 82 views
1

我想用Python語言編寫一個函數,它告訴,如果我給數是素數,到目前爲止我的代碼是:FUNCTION_NAME沒有定義錯誤

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() 

但我輸入後得到這個錯誤NUMER:

運行時間: -

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()函數的地方找不到它。感謝您的幫助

+0

「p」變量的定義在哪裏? –

+0

對於'p'我很抱歉,應該是'o'。但問題仍然存在。 –

+0

Okey,我修改了一下你的代碼嘗試它,在中間時間,我會寫一個解釋給你 –

回答

1

你寫出頭有點奇怪,所以我會解釋爲什麼這應該做你specting什麼:

這是你的代碼,我會字裏行間評論:

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() 
+0

感謝達米安,修改過的代碼工作。我試圖學習功能和他們互相呼叫的方式,所以我做了3個不同的功能,而不是一個。我將通過新代碼並解決問題。 –

+0

@Ritesh_BM我一直都很喜歡幫忙,如果你喜歡,不要忘記接受(✓)和投票:) –