Examples Python implement any number of a plurality of inputs, and calculates the average value of

Today small for everyone to share a number of Python implement any number of inputs, and examples of the average value calculation, a good reference value, we want to help. Follow small series together and come back
later learned about Python data types, functions, implemented with a segment string input any more data, and to calculate the average of the applet. The idea is to receive an input character string, a space for the separator, dividing the data into a list (LST1), the data is transferred into another LST1 empty list (LST), the string conversion when the dump integer, so the number determined by the function and the lst average, Python is a base (5) in the end of the program upgrade.

code show as below:

print("-----求平均值,可输入任意多个数-------")
lst = [] #定义一个空列表
str = raw_input("请输入数值,用空格隔开:")
lst1 = str.split(" ")#lst1用来存储输入的字符串,用空格分割
i = 0
while i <= len(lst1)+1:
 lst.append(int(lst1.pop()))#将lst1的数据转换为整型并赋值给lst
 i += 1
#print(lst)
def sum(list):
 "对列表的数值求和"
 s = 0
 for x in list:
 s += x
 return s
def average(list):
 "对列表数据求平均值"
 avg = 0
 avg = sum(list)/(len(list)*1.0) #调用sum函数求和
 return avg
print("avg = %f"%average(lst))

operation result:

-----求平均值,可输入任意多个数-------
请输入数值,用空格隔开:21 32 45 65
avg = 47.333333
 
***Repl Closed***

This procedure not only can be calculating an average value, may be applied to all the program requires a plurality of data inputs (completed within one line), a module is a small.
I write to you, for everyone to recommend a very wide python learning resource gathering, click to enter , there is a senior programmer before learning to share experiences, study notes, there is a chance of business experience, and for everyone to carefully organize a python zero the basis of the actual project data, daily python to you on the latest technology, prospects, learning to leave a message of small details

Any more than this number of inputs Python implementation, and examples of its average value is calculated Xiao Bian to share with you the entire contents of the

Published 22 original articles · won praise 9 · views 10000 +

Guess you like

Origin blog.csdn.net/haoxun08/article/details/104741044