Python is an example of inputting any number and calculating its average value

  • 2021-07-18 08:33:18
  • OfStack

After learning the knowledge of Python related data types and functions, a small program for inputting any number of data and calculating its average value is realized by using string segmentation. The idea is to receive the input string, take the space as the separator, store the divided data in the list (lst1), transfer the data in lst1 into another empty list (lst), and convert the string into integer type when transferring, so as to use the function to find the sum and average of the numbers in lst, which is an upgraded version of the ending program in Python Foundation (5).

The code is as follows:


print("----- Average, you can enter any number -------")
lst = [] # Definition 1 Empty list 
str = raw_input(" Please enter numeric values, separated by spaces :")
lst1 = str.split(" ")#lst1 Used to store the input string, divided by spaces 
i = 0
while i <= len(lst1)+1:
 lst.append(int(lst1.pop()))# Will lst1 To an integer type and assign a value to the lst
 i += 1
#print(lst)
def sum(list):
 " Sum the values of the list "
 s = 0
 for x in list:
 s += x
 return s
def average(list):
 " Average list data "
 avg = 0
 avg = sum(list)/(len(list)*1.0) # Call sum Function summation 
 return avg
print("avg = %f"%average(lst))

Run results:


----- Average, you can enter any number -------
 Please enter numeric values, separated by spaces :21 32 45 65
avg = 47.333333

***Repl Closed***

This program can not only calculate the average, can be applied to 1 cut need multiple data input (completed in 1 line) in the program, is a small module.


Related articles: