Ask coding questions

← Back to all posts
I am creating simple password in Python, how to set that only numbers can be input
marcporms (1)

I am confused on how to add code to filter the password inputs of the user to be numbers only, if they type letters there is message will show, "please input number only or else, how can i make the password to be can type numbers or letters? and lenght of the password should be up to 30 words only. Kindly help

Comments
hotnewtop
MarcusWeinberger (786)

In python, you can check if a string contains only numbers by using the isnumeric function of the string class.

Eg if you have a string called x which contains "5", x.isnumeric() will return True

marcporms (1)

@MarcusWeinberger, thanks, but how can I include this kind of code in my code, can you give me example. I will appreciate.

Vandesm14 (2727)

@marcporms

x = "5"
x.isnumeric() # => true

But:

x = "abc"
x.isnumeric() # => false
marcporms (1)

@Vandesm14 , thanks a lot. I will try this code.

Vandesm14 (2727)

@marcporms
Please mark my comment as the answer if I resolved your issue 👍

marcporms (1)

@Vandesm14 , hello, I am receiving error while doing your above example. the code is not recognize.

MarcusWeinberger (786)

@marcporms

password = input("password: ")
while not password.isnumeric():
    print("password must be numeric only")
    password = input("password: ")
password = int(password)
[deleted]

I would use this:

valid = False
while valid == False:
	password = input('Type a numbers only password')
	#your if statements and length/comparison stuff here.
	try:
		password = int(password)
		valid = True
		print('success!')
	except ValueError:
		import os
		os.system('clear')
		print('Your password can only have numbers!')

It loops around and it is the simplest way for bug-free verification.

[deleted]

You can use prompt toolkit

from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit import prompt

class NumberValidator(Validator):
    def validate(self, document):
        text = document.text

        if text and not text.isdigit():
            i = 0

            # Get index of fist non numeric character.
            # We want to move the cursor here.
            for i, c in enumerate(text):
                if not c.isdigit():
                    break

            raise ValidationError(message='This input contains non-numeric characters',
                                  cursor_position=i)

number = int(prompt('Give a number: ', validator=NumberValidator()))
print('You said: %i' % number)

It can detect if its a number or not, when the user presses enter. It can also do it on the fly, detecting when the user presses a key that is not a number.

from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit import prompt

class NumberValidator(Validator):
    def validate(self, document):
        text = document.text

        if text and not text.isdigit():
            i = 0

            # Get index of fist non numeric character.
            # We want to move the cursor here.
            for i, c in enumerate(text):
                if not c.isdigit():
                    break

            raise ValidationError(message='This input contains non-numeric characters',
                                  cursor_position=i)

number = int(prompt('Give a number: ', validator=NumberValidator(), validate_while_typing=True))
print('You said: %i' % number)

Read more about it here: prompt toolkit docs

marcporms (1)

@TaylorLiang, thank you for this information, i am getting much information from you guys, appreciate it so much...

Highwayman (1483)

Wait, just cast the input to an int and catch an error if it isn’t in a loop

X=0
while True:
  X = int(input("give me num")
  catch EVERYTHINGGGGG: # if err (I don’t know how to catch stuff in python
    continue # try again
  break

Edit:
Figured it out.

while True:
  try:
    x = int(input('num> '))
  except ValueError: # I think.
    print('only numbers\n')
  else 
    break
marcporms (1)

@Highwayman, thank you man, I am getting much details now for this kind of code, I will try all of your suggestion. Have a great day!