Homepage Forums Dev & Debugging How to validate user input?

  • How to validate user input?

     Vincent J. Gerner updated 7 months ago 3 Members · 3 Posts
  • Jayson Ferry

    Member
    December 25, 2020 at 9:49 am
    15 Coins
    0 Gems
    Level: Rookie

    Merry Christmas everyone. I have a question and might sound silly to some/most of you. But I am an absolute beginner.

    So I know that the below code is for taking user input. The only thing I want to learn is how do I validate the input to be numbers only?

    empid = input("Enter your employee identification number: ")
    print(empid)

    I want to accept only numbers. Not alphanumeric.

  • Darion Larson

    Member
    December 25, 2020 at 8:34 pm
    17 Coins
    0 Gems
    Level: Rookie
    Helpful
    Up
    0
    Down
    Not Helpful

    You can use the data type required to specify.

    x = int(input("Please enter a number: "))
    print(x)
  • Vincent J. Gerner

    Member
    December 26, 2020 at 10:28 am
    321 Coins
    71 Gems
    Helpful
    Up
    0
    Down
    Not Helpful

    Using ValueError will be a much better way.

    try:
    empid=int(input("PLease enter employee ID "))
    except ValueError:
    print("Please enter a valid number ")
    if empid == 1100345002:
    print("Your entry has been registered.")
    else:
    print("Sorry the ID is not recognised.")

Log in to reply.

Original Post
0 of 0 posts June 2018
Now

New Report

Close