用等位数做浮标?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (22)
a = raw_input('How much is 1 share in that company? ')

while not a.isdigit():
    print("You need to write a number!\n")
    a = raw_input('How much is 1 share in that company? ')

只有当用户输入integer,但我希望它能工作,即使他们进入float,但当他们进入string

因此,用户应该能够同时输入两个99.2,但不是abc

提问于
用户回答回答于

使用正则表达式。

import re

p = re.compile('\d+(\.\d+)?')

a = raw_input('How much is 1 share in that company? ')

while p.match(a) == None:
    print "You need to write a number!\n"
    a = raw_input('How much is 1 share in that company? ')
用户回答回答于

EAFP

try:
    x = float(a)
except ValueError:
    print("You must enter a number")

扫码关注云+社区