python - 我的基本 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)
解决方案
你正在做:
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
推荐阅读
- python - tkinter 的 Python 问题
- javascript - 如何在手机上隐藏下拉菜单的子链接?
- azure - 发布带有 React + 身份验证的 Asp.net core 3.1.3 到 Azure Linux App Service 不起作用
- spring-security - 即使使用 antmatcher 许可,带有 Keycloak 的 Spring Security 也会重定向到登录
- django - WebSocket握手期间的Django-channels错误:意外的响应代码:404
- python - 试图理解面向对象的编程。如何使用对象组合?
- angular - RxJS distinct 运算符没有从对象数组中获取不同的值
- reactjs - 动态需要图像在 reactjs/nextjs 中不起作用
- swift - 为什么我的 UILabel 无法显示成功获取的值?
- java - 可以将两个参数传递给模态