为什么我必须在此代码中输入两次数字

时间:2015-08-04 01:44:10

标签: python

def numList(): 
    values = [] 
    while True: 
         numbers = int(input("Enter any amount of numbers or -9999 to quit: "))
         if numbers == -9999:break
         values.append(numbers)

    return values



def AvgAllNum(values): 
    allNum = [] 
    average = 0 
    for i in values: 
         allNum.append(i) 
    average = sum(allNum)/len(allNum) 
    return average

def AvgPositive(values): 
    posNum = [] 
    average = 0 
    for i in values: 
         if i > 0: 
              posNum.append(i) 
              average = sum(posNum)/len(posNum) 
    return average

def AvgNonPos(values): 
    nonNum = [] 
    average = 0 
    for i in values:
        if i < 1: 
              nonNum.append(i) 
              average = sum(nonNum)/len(nonNum) 
    return average

def dictionary():

     return {'all': AvgAllNum(), 'pos': AvgPositive(), 'def': AvgNonPos()}() 

print("Your list of numbers are", numList())    
print("Enter your numbers again to get the averages and -9999 to return averages")




values = numList()


print("Your Averages Are")    
print('allNum', AvgAllNum(values), 'posNum', AvgPositive(values), 'NonNum', AvgNonPos(values))

1 个答案:

答案 0 :(得分:2)

这是因为首先你打印行中的numList()为 -

print("Your list of numbers are", numList()) 

然后你再次在这里打电话 -

values = numList()

所以你要求两次数字,但只是第二次,你实际上保存输入的数字。你第一次打印它们然后扔掉它们。

values = numList()来电后移动打印并改为打印values。示例 -

print("Enter your numbers again to get the averages and -9999 to return averages")

values = numList()
print("Your list of numbers are", values)    

print("Your Averages Are")    
print('allNum', AvgAllNum(values), 'posNum', AvgPositive(values), 'NonNum', AvgNonPos(values))