【问题标题】:isalpha() and isascii() with parentheses causing errors, but not withoutisalpha() 和 isascii() 带括号导致错误,但并非没有
【发布时间】:2019-08-03 11:31:55
【问题描述】:

这些括号的目的是什么?为什么会出现错误?

这是我在a.isalphaa.isascii 之后用括号键入ASCII 字符时收到的错误:

Traceback(最近一次调用最后一次): 文件“C:/---/---/PycharmProjects/PythonExercicios/test.py”,第 4 行,在 a1 = 浮动(一) ValueError:无法将字符串转换为浮点数:'!'

a = str(input('Type the "a" side of the triangle: ')).strip()
while a.isascii() and a.isalpha():
    a = input('Please, type again using only numbers: ')
a1 = float(a)

【问题讨论】:

  • 可以打字母的,怎么能转换成float?最后一条语句。
  • @Lamanus 如果他们输入了字母,while 循环将识别并再次提示输入不同的输入。
  • @JohnGordon 哦,是的,我错过了,但是 isascii() 只在 python 3.7 中工作,而不是在其他版本中,我应该先询问提问者使用的 python 版本
  • 这是 while 循环目标,强制用户在输入时只使用数字
  • a1 = float(a.replace(',', '.')) 这是 'a' 转换为 float 的更好版本

标签: python


【解决方案1】:

while 循环在输入感叹号时退出,因为它是 ascii 但不是字母数字。

然后它转到下一行,float() 抛出错误,因为! 无法转换为浮点数。

也许你想要这个?

while not a.isdigit():

【讨论】:

  • 谢谢你,你让 python 程序员的夜晚更快乐了 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-04-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 1970-01-01
相关资源
最近更新 更多