Ask coding questions

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

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

Answered by TimothyAnderso1 (55) [earned 5 cycles]
View Answer
Commentshotnewtop
1
TimothyAnderso1 (55)

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! ")
2
TheDrone7 (504)

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
else:
  # the input does not have 4 characters/digits.
1
ArchieMaclean (518)

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

1
TheDrone7 (504)

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

1
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: https://repl.it/@Dopest_Pleb/Bulls-and-cows

1
Lord_Poseidon (108)

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

1
ArchieMaclean (518)

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 :)