2017-10-19 35 views
0

我試圖在python中重複地請求輸入,並且一旦輸入字符串'q'就會中斷循環並返回輸入的平均值。我不知道爲什麼這不起作用。循環輸入並找到輸入q時的列表的平均值

def listave(list): 
    UserInput = input('Enter integer (q to quit):') 
    list.append(UserInput) 
    while UserInput != 'q': 
     UserInput = input('Enter integer (q to quit:)') 
     if isinstance(UserInput, int) == True: 
      list.append(UserInput) 
     elif UserInput == 'q': 
      break 
    list.pop() 
    print('Average: ', float(sum(list)/len(list))) 

listave(list) 

回答

0

首先,不要從列表中選擇pop。無需因爲您永遠無法將'q'附加到list。其次,輸入後需要轉換爲int,否則isinstance將無法​​工作。

0

你的代碼中有幾個問題。首先,list是一個內置的定義,重載它的定義不是一個好習慣。

您使用pop,但沒有理由。 'q'的值不會被添加到列表中。

最後,input總是返回一個字符串。所以你需要在追加到列表之前將其轉換爲數字。

這是您的代碼的修改,試圖將輸入轉換爲浮點數,除非'q'是輸入。如果它不能,它會打印一條消息並繼續。

def listave(my_list): 
    UserInput = '' 
    while UserInput != 'q': 
     UserInput = input('Enter integer (q to quit:)') 
     if UserInput == 'q': 
      break 
     try: 
      x = float(UserInput) 
      my_list.append(x) 
     except ValueError: 
      print('Only numeric values and "q" are acceptable inputs') 
    print('Average: ', float(sum(my_list)/len(my_list))) 

listave([]) 
-1

如果你正在運行的Python 2,請確保您正在使用raw_input(),而不是input()(在Python 3,你應該總是使用input()

def get_average(): 
    ls = [] 
    user_input = 0 
    while user_input != 'q': 
     user_input = raw_input('Enter inter (q to quit):') 
     if user_input != 'q': 
      ls.append(int(user_input)) 
     elif user_input == 'q': 
      break 
    ls.pop() 
    return sum(ls), ls 

print get_average() 

# ls.pop() will delete the last number of input 
0

,而不是試圖修改答案匹配原始代碼。這是更pythonic版本。作爲下一級別,也可以使用atexit編寫。

def avg(): 
    l = [] 
    while True: 
     i = input("Enter integer (q to quit:) ") 
     if i.strip() == "q": 
      a = float(sum(l))/ len(l) 
      print("Average: ", a) 
      return a 
     else: 
      try: 
       l.append(float(i)) 
      except ValueError: 
       print('Only numeric values and "q" are acceptable inputs') 

if __name__ == "__main__": 
    avg() 
0

如果你願意從functools導入,您可以使用partial類和iter功能,可採取定點參數告訴在終止其輸入迭代器。

from functools import partial 

def listave(list): 
    UserInput = iter(partial(input, 'Enter integer (q to quit):'), 'q') 

    for inp in UserInput: 
     try: 
      list.append(int(inp)) 
     except ValueError: 
      pass 

    print('Average: ', float(sum(list)/len(list))) 

listave(list)