Python用户只能输入浮点数

2024-04-20 13:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找出如何让用户[只输入数字<;0]和[不允许字母]使用。有人能告诉我怎么做吗。我试着设置try/catch块,但总是出错。在

edgeone = input("Enter the first edge of the triangle: ")

Tags: ofthe用户ltinput字母数字first
3条回答

我想你只想要数字大于0,还是要小于零?无论如何,你可以在while循环中使用try/except。在

对于python3,我认为您正在使用它?

goodnumber = False
while not goodnumber:
    try:
        edgeone = int(input('Enter the first edge of the triangle:'))
        if edgeone > 0:
            print('thats a good number, thanks')
            goodnumber = True
        else:
            print('thats not a number greater than 0, try again please')
    except ValueError:
        print('Thats not a number, try again please')

希望这有帮助。在

对于这种情况,必须使用except处理程序:

try:
    value = int(raw_input("Enter your number:"))
    if not ( value < 0 ):
        raise ValueError()
except ValueError:
    print "you must enter a number <0 "
else:
    print value #or something else 

这个问题在这里已经有了答案:Accepting only numbers as input in Python

你可以这样做。在

i = 1
while(type(i)!=float):
    i=input("enter no.")
    try:
        int(i):
    except:
        try:
            i = float(i)
        except:
            pass
print(i)

相关问题 更多 >