python输入一系列的值_如何在python中计算用户输入

这篇博客讨论了一个Python程序的逻辑错误,指出在获取用户输入时应将每个数字存储到列表中,并在用户输入完成后计算平均值。文章提供了一个修改后的代码示例,该示例使用while循环收集用户输入的分数,将其转换为整数并添加到列表中。当用户输入'done'时,程序计算并打印出平均成绩,使用内置的sum函数和len函数来实现。
摘要由CSDN通过智能技术生成

你的逻辑有一些缺陷。在每次在main()中请求用户输入时,都会覆盖user_input的值。您应该做的是,将每个数字收集到list()中。在

Python所引发的错误告诉您的是,内置函数sum()接受传入的一系列数字,而不是单个数字。在

input()函数返回一个字符串,因此需要将输入转换为整数。在

我会把你的程序改写如下:def main():

# create a list to store each grade

# that the user inputs.

grades = []

# while forever

while True:

# get input from the user.

# I am not converting the input to a integer

# here, because were expecting the user to

# enter a string when done.

i = input("Enter grade: ")

# if the user enters 'done' break the loop.

if i == 'done':break

# add the grade the user entered to our grades list.

# converting it to an integer.

grades.append(int(i))

# print the return value

# of the avg function.

print("Grade average:", avg(grades))

def avg(grades):

# return the average of

# the grades.

# note that I'm using the builtin round()

# function here. That is because

# the average is sometimes a

# long decimal. If this does not matter

# to you, you can remove it.

return round(sum(grades)/len(grades), 2)

# call the function main()

main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值