简体   繁体   中英

I want to take an input from a user but receive only numbers.in Python

i am trying to make a program were a user will input his phone. I want him to be able to write only numbers and if he writes a letter then it will either delete the character he just wrote or "lock" his keyboard to only numbers. I am currently using a try/except in order to work but still i want to know if there is a library or a function that allows me to give access to only certain keys to the user. Thank you in advance!

You can use while to loop the input till the user inputs only number:

def getInput():
    value = input("Please enter number: ")
    while not value.isnumeric():
        print("Invalid number")
        value = input("Please enter valid number: ")
    return int(value)
getInput()

You cannot "restrict" the keys a user can type with the input() function itself. You could (as far as I can tell - I didn't try actually) get this result on unix-like systems using the curses module, but you'll need some external lib to make it work on Windows. And in all cases, it will requires much more coding (curses is not exactly a simple, modern UI lib).

As a side note, a phone number can contains non numeric characters (think of international phone numbers) ;-)

You cannot stop an input like that, but you can use a try-except statement.
Either by asking for the input again or returning a print error.

try:
    user_input = int(input("Number input: "))
except ValueError:
    user_input = int(input("Number input: "))

Similarly, if you want this to repeat until the user inputs a number you can use a while loop and break.

while True:
    try:
        user_input = int(input("Number input: "))
        if int(user_input):
            break
    except ValueError:
        print("Input is not an number")
    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM