gpt4 book ai didi

python - 用户输入平均值

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:49 25 4
gpt4 key购买 nike

我的老师不在类里面教我们,我正在努力自学。这是我应该做的,这是我已经做到的。任何帮助将不胜感激!

  • Takes a list of five numbers from the user
  • Prints the list
  • Prints the average
  • Modifies the list so each element is one greater than it was before
  • Prints the modified list
 def average():
x=a+b+c+d+e
x=x/5
print("the average of your numbers is: " +x+ ".")

my_list =[ ]
for i in range (5):
userInput = int(input("Enter a number: ")
my_list.append(userInput)
print(my_list)
average(my_list)

感谢您的帮助,您的 pipe 只能走这么远了!

最佳答案

The main functions that are going to be useful to you here are sum() and len()

sum()返回可迭代项的总和

len()返回 python 对象的长度

使用这些函数,您的案例也很容易应用:

my_list = []
plus_one = []

for x in range(5):
my_list.append(x)
plus_one.append(x+1)

print my_list
print plus_one

def average():
average = sum(my_list) / len(my_list)
return average

print average()

正如 Shashank 指出的那样,推荐的方法是在函数中定义一个参数,然后在调用函数时传递列表的参数。不确定您是否已经了解参数,所以我最初将其排除在外。无论如何,它在这里:

def average(x):
# find average of x which is defined when the function is called

print average(my_list) # call function with argument (my_list)

这样做的好处是,如果您有多个列表,则不需要新函数,只需更改函数调用中的参数即可。

关于python - 用户输入平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19190739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com