Limit user input to 3 integers

I want to change the requirement to enter numbers to allow only three numbers.

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

What do I need to change to adapt a ValueError?

+4
source share
4 answers

Why are you just simply restricting your input to three digits:

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

If you have problems with numbers starting with 0, you can do the following:

shootnum = (int(input("Enter today shoot number > ")))
shootnum = (str(shootnum))
shootnum = int(shootnum[:3])
print((shootnum))
-2
source

Just say:

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

1 regex (inspired by Maarten Fabre)

import re

while True:
    try:
        shoot = raw_input("Enter today 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 just check if the arrow is a three-digit number

while True:
    try:
        shoot = raw_input("Enter today 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.")

results below

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

Just check the length

user_input = input()
if len(user_input.strip()) != 3:
    raise Exception('3 digits allowed')

You still need to check that the number is entered

0
source

Source: https://habr.com/ru/post/1664771/


All Articles