Search code examples
functionvalidationinputwhile-loopinteger

Python- Return a verified variable from a function to the main program


Can anyone please direct me to an example of where one can send a user input variable to a checking function or module & return the validated input assigning / updating the initialised variable?. I am trying to re-create something I did in C++ many years ago where I am trying to validate an integer! In this particular case that the number of bolts input in a building frame connection is such. Any direction would be greatly appreciated as my internet searches and trawls through my copy of Python A Crash Course have yet to shed any light! Many thanks in anticipation that someone will feel benevolent towards a Python newbie! Regards Steve

Below is one on my numerous attempts at this, really I would just like to abandon and use While and a function call. In this one apparently I am not allowed to put > (line 4) between str and int, this desite my attempt to force N to be int - penultimate line!

def int_val(N):
    #checks
    # check 1.  n > 0 for real entries
    N > 0
    isinstance(N, int)
    N=N
    return N
    print("N not ok enter again")
    #N = input("Input N the Number of bolts  ")
    

# Initialiase N=0
#N = 0

# Enter the number of bolts
N = input("Input N the Number of bolts  ")
int_val(N)

print("no of bolts is", N)

Solution

  • Is something like this what you have in mind? It takes advantage of the fact that using the built-in int function will convert a string to an integer if possible, but otherwise throw a ValueError.

    def str_to_posint(s):
        """Return value if converted and greater than zero else None."""
        try:
            num = int(s)
            return num if num > 0 else None
        except ValueError:
            return None
    
    while True:
        s = input("Enter number of bolts: ")
        if num_bolts := str_to_posint(s):
            break
        print(f"Sorry, \"{s}\" is not a valid number of bolts.")
        
    print(f"{num_bolts = }")
    

    Output:

    Enter number of bolts:  twenty
    Sorry, "twenty" is not a valid number of bolts.
    Enter number of bolts:  20
    num_bolts = 20