python - ValueError:无法将字符串转换为浮点数:'F' python
问题描述
我正在尝试编写一个小的 python 代码来打印出用户提供的数据总和。更具体地说,当事先不知道数据数量时,我需要代码能够计算它。为了实现这一点,我需要代码来识别用户没有指示列表的大小,并通过键入“F”来知道要包含的最后一个条目是什么。我的代码遇到的问题(见下文)是,当我使用“F”而不是“-1”时,代码崩溃并显示以下消息“ValueError:无法将字符串转换为浮点数:'F' python”。谁能帮我理解我做错了什么,所以我可以解决它。
numberList = []
count = int(input("Enter the list size :"))
stopList = False
F = -1
mysum = 0
num = 0
if count >= 0:
for i in range(0, count):
item = int(input("Enter number :"))
numberList.append(item)
mysum = sum(numberList)
print("The sum is", mysum)
if count < 0:
while stopList is False:
nextnum = float(input("Enter number :"))
if nextnum == F:
stopList = True
if stopList is False:
num += 1
mysum += nextnum
print("The sum is", mysum)
解决方案
我将只解决代码中存在问题的部分,即if count < 0:
.
您应该首先按原样获取输入并检查它是否是'F'
,然后才将 if 转换为浮动,如有必要:
while stopList is False:
nextnum = input("Enter number :")
if nextnum == 'F':
stopList = True
if stopList is False:
num += 1
mysum += float(nextnum)
print("The sum is", mysum)
作为旁注,不要将这样的条件用于循环,我会这样使用它:
while True:
nextnum = input("Enter number :")
if nextnum == 'F':
break
num += 1
mysum += float(nextnum)
print("The sum is", mysum)
推荐阅读
- python - 从 .xlsx 中的列中读取数据,并使用 python 将每个列保存为单独的 .txt 文件
- leaflet - 如何为通过geojson数据搜索的传单创建侧面板自定义搜索?
- javascript - useEffect 挂钩依赖项未更新
- ios - 'OSSpinLock' 在 iOS 10.0 中被弃用:使用 os_unfair_lock() from
反而 - virtual-machine - 无法在 ubuntu 16.04 上运行 couchbase
- javascript - 如何从所有 [pre] 标签中找出所有 [0-9,az,AZ] 并为它们添加颜色?
- kubernetes - 并行使用 helm 2 和 helm 3 是否有任何问题?
- asp.net - 无法在两个服务之间进行通信
- asp.net-mvc-4 - 我尝试使用 Microsoft 帐户登录,但出现此错误消息“处理请求时数据库操作失败”。
- android - 打开文件意图的自定义扩展名(强制扩展名)