How to find average using python
After learning the knowledge of Python related data types and functions, I used string segmentation to implement a small program that inputs any multiple data and calculates their average. The idea is to receive the input string, use spaces as delimiters, store the divided data in a list (lst1), transfer the data in lst1 to another empty list (lst), and convert the string when transferring It is an integer type, so the function can be used to find the sum and average of the numbers in lst.
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))
Run result:
Please enter the value, separated by spaces: 21 32 45 65 avg = 47.333333
The above is the detailed content of How to find average using python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

Fastapi ...

Using python in Linux terminal...

Understanding the anti-crawling strategy of Investing.com Many people often try to crawl news data from Investing.com (https://cn.investing.com/news/latest-news)...
