首页 > 解决方案 > 我的基本 Python 代码中用于计算数字总和的逻辑缺陷?

问题描述

我不得不使用'try'和'except'来计算数字总和和无效输入的帐户。当用户输入“完成”时,程序会打印出结果。他有什么错误?

total = 0
count = 0
while True :
    try :
      x = (input('enter an input \n'))
      y = float(x)
      print('your number is : ', y)
      count = count+1
      total = total + x
    except :
      if x == 'done':
          break
      else :
          print('invalid input')

print ('sum is' , total , 'and average is' , total/count)

标签: python

解决方案


你正在做:

  x = (input('enter an input \n'))
  y = float(x)
  print('your number is : ', y)
  count = count+1
  total = total + x

即尝试将total用户输入的内容添加为str,您应该添加浮点值,即:

  x = (input('enter an input \n'))
  y = float(x)
  print('your number is : ', y)
  count = count+1
  total = total + y

推荐阅读