Python Forum
how to make sure an input is from the wanted type
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
how to make sure an input is from the wanted type
#6
I tend to use a custom function when checking any (and all) user input.

As a simple example:

def check_input(n):
    """check the user input for a valid number.
    if valid, return the number, otherwise return 'None'"""
    for number in n:
        if number.isnumeric():
            pass
        else:
            return None
    return n


user_input = check_input(input("Pick a number: "))
if user_input:
    print(f"You picked {user_input}")
else:
    print("Not valid.\nNumbers need to be whole (no decimal point)")

That function can be coded to return anything you choose (such as an error message) and do whatever checks you want, such as checking that a number is within a certain range.

Clearly, as is, the number being printed is a string object, but again, the function could return a int, or a float, or the object type can be changed after it has been returned; it's a matter of choice.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply


Messages In This Thread
RE: how to make sure an input is from the wanted type - by rob101 - Oct-26-2022, 08:30 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to make input come after input if certain line inserted and if not runs OtherCode Adrian_L 6 3,437 Apr-04-2021, 06:10 PM
Last Post: Adrian_L
  Make the answer of input int and str enderfran2006 2 2,084 Oct-12-2020, 09:44 AM
Last Post: DeaD_EyE
  How to make input goto a different line mxl671 2 2,545 Feb-04-2020, 07:12 PM
Last Post: Marbelous
  Type hinting - return type based on parameter micseydel 2 2,578 Jan-14-2020, 01:20 AM
Last Post: micseydel
  how can i handle "expected a character " type error , when I input no character vivekagrey 2 2,834 Jan-05-2020, 11:50 AM
Last Post: vivekagrey
  catch input type error mcmxl22 5 3,206 Aug-11-2019, 07:33 AM
Last Post: wavic
  Getting type from input() function in Python 3.0 leodavinci1990 7 3,911 Jul-29-2019, 08:28 PM
Last Post: avorane
  how i can check the input type? Firdaos 3 2,931 Dec-13-2018, 11:39 PM
Last Post: wavic
  How to make an input trigger the output once no matter how long input is high cam2363 3 3,348 Feb-05-2018, 01:19 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020