Ask coding questions

← Back to all posts
Checking that a user input has four digits
IsobelBolter (2)

how do you check that a user input has four digits?

Answered by TimothyAnderso1 (65) [earned 5 cycles]
View Answer
TimothyAnderso1 (65)

Makin it simple again cause i can lmao

x = input() ## Asks for user input
has4digits = false ## Lets you know if you got 4 digits

for char in x: ## For Every character in x
   num = num + 1 ## Num = num + 1
   if num >= 4:
       has4digits = true

if has4digits = true:
    print(" :D I have 4 digits! ")
TheDrone7 (665)

The best way would be similar to what Archie suggested, but first convert it to a string which would make the code look something like this

x = input ()
if len(str(x)) == 4:
  # the input has 4 characters/digits
  # the input does not have 4 characters/digits.
ArchieMaclean (687)

@TheDrone7 When you get input it's already a string though.

TheDrone7 (665)

@ArchieMaclean They might take input as an integer or a list. Just to be safe converting it to a string would be better.

Dopest_Pleb (15)

Check if the length of their input is equal to 4. If it is, convert their input to an integer. Put this inside a try statement that catches a ValueError. Inside the catch you can continue the while loop to ask them again. If an error is not caught, then write the rest of the code for the program.

Here is my example:

Lord_Poseidon (111)

There is more than one method. You could do number in range(1000,10000) or even math.floor(math.log(number,10))==3 or as Archie said, the inbuilt len to find out the length of a string

ArchieMaclean (687)

You can check the length of a string with the len function, e.g.

if len(guess) != 4:
  print("Invalid Input")

Please mark this as the answer if it solved your problem :)