Python implements inputting five numbers and calculating the average

王林
Release: 2020-05-07 13:38:46
Original
15688 people have browsed it

Python implements inputting five numbers and calculating the average

Idea:

Receive the input string, use spaces as delimiters, store the divided data in the list (lst1), and convert the data in lst1 Store it in another empty list (lst), convert the string into an integer when transferring, and use the function to find the sum and average of the numbers in lst.

Example code:

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))
Copy after login

Run result:

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

***Repl Closed***
Copy after login

Recommended tutorial:python tutorial

The above is the detailed content of Python implements inputting five numbers and calculating the average. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template