Подтвердить что ты не робот

Использование isdigit для поплавков?

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.

Таким образом, пользователь должен иметь возможность вводить как 9, так и 9.2, но не abc.

Как мне это сделать?

4b9b3361

Ответ 1

Используйте регулярные выражения.

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? ')

Ответ 2

ЭСПЦ

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

Ответ 3

Существующие ответы правильны в том, что более Pythonic-путь обычно равен try...except (т.е. EAFP).

Однако, если вы действительно хотите выполнить проверку, вы можете удалить ровно 1 десятичную точку перед использованием isdigit().

>>> "124".replace(".", "", 1).isdigit()
True
>>> "12.4".replace(".", "", 1).isdigit()
True
>>> "12..4".replace(".", "", 1).isdigit()
False
>>> "192.168.1.1".replace(".", "", 1).isdigit()
False

Обратите внимание, что это не относится к float, отличному от int. Вы можете добавить эту проверку, если она вам действительно нужна.

Ответ 4

Я думаю, что @dan04 имеет правильный подход (EAFP), но, к сожалению, реальный мир часто является частным случаем, и для управления вещами действительно требуется некоторый дополнительный код, поэтому ниже более сложный, но также немного более прагматичный ( и реалистично):

import sys

while True:
    try:
        a = raw_input('How much is 1 share in that company? ')
        x = float(a)
        # validity check(s)
        if x < 0: raise ValueError('share price must be positive')
    except ValueError, e:
        print("ValueError: '{}'".format(e))
        print("Please try entering it again...")
    except KeyboardInterrupt:
        sys.exit("\n<terminated by user>")
    except:
        exc_value = sys.exc_info()[1]
        exc_class = exc_value.__class__.__name__
        print("{} exception: '{}'".format(exc_class, exc_value))
        sys.exit("<fatal error encountered>")
    else:
        break  # no exceptions occurred, terminate loop

print("Share price entered: {}".format(x))

Использование образца:

> python numeric_input.py
How much is 1 share in that company? abc
ValueError: 'could not convert string to float: abc'
Please try entering it again...
How much is 1 share in that company? -1
ValueError: 'share price must be positive'
Please try entering it again...
How much is 1 share in that company? 9
Share price entered: 9.0

> python numeric_input.py
How much is 1 share in that company? 9.2
Share price entered: 9.2

Ответ 5

s = '12.32'
if s.replace('.', '').replace('-', '').isdigit():
    print(float(s))

Обратите внимание, что это будет работать и для отрицательного float.

Ответ 6

Основываясь на ответе dan04:

def isDigit(x):
    try:
        float(x)
        return True
    except ValueError:
        return False

использование:

isDigit(3)     # True
isDigit(3.1)   # True
isDigit("3")   # True
isDigit("3.1") # True
isDigit("hi")  # False