将用户输入限制为3个整数

时间:2016-12-24 13:53:51

标签: python python-2.7

我想更改输入数字的要求只允许三位数。

shootnum = None
while True:
    try:
        shootnum = int(input("Enter today's shoot number > "))
        break
    except ValueError:
        print("Invalid number, please try again.")

我需要更改什么才能适应ValueError?

3 个答案:

答案 0 :(得分:0)

请说:

if x <= 999 and x >= 100:
    print("Yes")
else:
    print("No.")

答案 1 :(得分:0)

1个正则表达式(灵感来自MaartenFabré)

import re

while True:
    try:
        shoot = raw_input("Enter today's shoot number > ") # I use python 2.7
        shootnum = int(shoot)
        if not re.match(r'\d{3}$', shoot):
            raise ValueError # can be caught by except
        print shootnum
    except ValueError:
        print("Invalid number, please try again.")

2只检查拍摄是否是三位数

while True:
    try:
        shoot = raw_input("Enter today's shoot number > ") # I use python 2.7
        shootnum = int(shoot)
        if len(shoot) != 3 or shoot[0] == '-':
             raise ValueError # can be caught by except
        print shootnum
    except ValueError:
        print("Invalid number, please try again.")

结果低于

Enter today's shoot number > qwer
Invalid number, please try again.
Enter today's shoot number > -12
Invalid number, please try again.
Enter today's shoot number > 123
123
Enter today's shoot number > 1222
Invalid number, please try again.
Enter today's shoot number > 012
12
Enter today's shoot number > 0122
Invalid number, please try again.
Enter today's shoot number > 0
Invalid number, please try again.
Enter today's shoot number > 00
Invalid number, please try again.
Enter today's shoot number > 000
0
Enter today's shoot number > 0000
Invalid number, please try again.

答案 2 :(得分:-2)

为什么不简单地将输入限制为3位数:

shootnum = int(input("Enter today's shoot number > ")[:3])
print(shootnum)

如果您遇到以0开头的数字问题,那么您可以执行以下操作:

shootnum = (int(input("Enter today's shoot number > ")))
shootnum = (str(shootnum))
shootnum = int(shootnum[:3])
print((shootnum))