2014-08-28 70 views
0

我的代碼的show_list功能不起作用。我收到一條消息,指出'multiples'未定義,但我無法確定問題。有人可以請審查和建議,以什麼是我做錯了。幫助功能不起作用

def main(): 
    input1 = int(input("enter the low integer: ")) 
    input2 = int(input("enter the high integer: ")) 
    input3 = int(input("enter the integer for the multiples: ")) 

    show_multiples(input1, input2, input3) 

    print ("List was created") 


def show_multiples(input1, input2, input3): 

    num_range = range(input2, input1, -1) 
    multiples = [] 

    for num in num_range: 
     if num % input3 == 0: 
      multiples.append(num) 
      return multiples 


    show_list(multiples) 

def show_list(multiples): 

    elem = len(multiples) 
    average = sum(multiples)/elem 
    num_range = range(input2, input1, -1) 

    print ("the list has", elem, "elements.") 

    for num in num_range: 
     if num % input3 == 0: 
     print (num, end=" ") 

    print ("Average of multiples is ", average) 



main() 

回答

0

mutliples沒有在全球範圍內定義,只有在show_multiples()

範圍

你可能想要做的是在全球範圍內,改變

show_multiples(input1, input2, input3) 

multiples = show_multiples(input1, input2, input3) 
+0

感謝您的反饋 – user3988476 2014-08-29 02:02:18

1

你叫show_list(multiples)您定義的函數之前show_list

把你的主要功能,在你的代碼的結束和調用的main()來運行它:

def main(): 

    input1 = int(input("enter the low integer: ")) 
    input2 = int(input("enter the high integer: ")) 
    input3 = int(input("enter the integer for the multiples: ")) 

    show_multiples(input1, input2, input3) 

print ("List was created") 
main() 

只是調用show_list(multiples)將其移動到show_list定義的位置

您將會遇到更多問題:

def show_list(multiples): 
    elem = len(multiples) 
    average = elem/sum(multiples) 
    print ("the list has", elem, "elements.") 
    # num_range not defined only exists in show_multiples and input3 is also not accessable 
    for num in num_range: 
     if num % input3 == 0: 
      multiples.append(num) 
      print (num) 

不能完全確定你想要什麼,但我想這將讓你更接近:

input1 = int(input("enter the low integer: ")) 
input2 = int(input("enter the high integer: ")) 
input3 = int(input("enter the integer for the multiples: ")) 
num_range = range(input2, input1, -1) 

def show_multiples(): 
    multiples = [] 
    for num in num_range: 
     if num % input3 == 0: 
      multiples.append(num) 
    return multiples 

def show_list(): 
    multiples = show_multiples() 
    elem = len(multiples) 
    average = elem/sum(multiples) 
    print ("the list has", elem, "elements.") 
    for num in num_range: 
     if num % input3 == 0: 
      multiples.append(num) 
     print (num) 

show_list()