python - 当我尝试使用 pycharm 时,我遇到了一个奇怪的 python 问题
问题描述
我用python写了一个长度转换器,代码如下:
active = True
while active:
option = input('please choose:\na:centimetre to inch \nb:inch to centimetre:')
if option == "a":
centimetre = input('Please enter centimetre:')
centimetre= float (centimetre)
inch = centimetre / 2.54
print(str(centimetre) + ' centimetre equals' + str(inch) + ' inches')
elif option == "b":
inch = input('Please enter inch:')
inch = float ( inch )
centimetre = inch * 2.54
print(str(inch) + ' inch equals ' + str(centimetre) + ' centimetre')
else:
print("sorry you entered wrong option。please enter 'a'or'b': ")
continue
status = input('continue? yes/no :')
if status == 'no':
active = False
这些代码在notepad++和 http://www.pythontutor.com/上运行就可以了
但是当我尝试使用pycharm时,出现错误:
line 6, in <module>
centimetre= float (centimetre)
ValueError: could not convert string to float:
不知道问题出在哪里。有没有人遇到过这个问题?
解决方案
您可以尝试检查输入是否能够转换为浮点数,使用try:
.
而且,如果 Python 无法将逗号识别为小数点,并且可能将句点识别为千位分隔符是一个问题,那么您可以检查是否交换了逗号和句点的数字(使用该.replace()
方法)。
这方面的一个例子是:
x = '2.3'
y = '3,4'
def isnumber(num):
try:
float(num)
return True
except ValueError:
try:
float(num.replace(',', 'A').replace('.', 'B').replace('A', '.').replace('B', ','))
return True
except ValueError:
return False
if isnumber(x):
print(f'The number {x} is valid.')
else:
print(f'The number {x} is not valid.')
print()
if isnumber(y):
print(f'The number {y} is valid.')
else:
print(f'The number {y} is not valid.')
推荐阅读
- c# - 如何解决实体框架的“不支持每种类型的多个对象集”问题
- c++ - 类层次结构中的运算符重载
- excel - 通过Excel中的公式设置单元格的背景颜色
- excel - 从对话框中获取文件名
- r - 如何将 R 输出写入 Xlsx?
- python - 蟒蛇 | 网络抓取用户评论
- mysql - LEFT JOIN 返回第一个表的所有结果
- asp.net-mvc - 如何仅显示 MVC 中数据库表中的特定记录?
- c# - 如何在视图中返回 HTTP BadResponse 消息?
- angular - 日期时间选择器在时间戳中添加 00:00:00,我想要当前时间而不是 2020 年 5 月 27 日星期三 00:00:00 GMT+0530(印度标准时间)