2017-10-19 158 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)