Home > database >  How to use try/except blocks for multiple variables that require user input?
How to use try/except blocks for multiple variables that require user input?

Time:11-13

while True:
    try:
        age = int(input("Enter your age: "))
        if age <= 0:
            raise TypeError("Enter a number greater than zero")
    except ValueError:
        print("Invalid age. Must be a number.")
    except TypeError as err:
        print(err)
    except:
        print('Invalid input')
    break 
while True:   
    try:
        height = float(input('Enter your height in inches: '))
        if height <= 0:
            raise TypeError("Enter a number greater than 0")
        break
    except ValueError:
        raise ValueError("Height must be a number.")

I have multiple variables that need user input in order for the program to run. I need to get 3 variables from a user and they need to input the values correctly. I thought I should use try/except blocks for each of the variables but when I use the try/except block for the first variable and begin writing the second block the program skips over the exceptions even if the user input is incorrect.

I thought about using another while loop but I'm not sure how to write in python the idea of; if previous condition is met move onto next block of code. I tried using the same try/except block for two variables and failed. Any insight would be helpful. The problem is that when an incorrect value is entered the program still continues onto the next try block.

CodePudding user response:

You can put your user input request into a function that is called for each unique variable see the following as an example:

# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
    while True:
        resp = input(prompt)
        if respType == str or respType == None:
            break
        else:
            try:
                resp = respType(resp)
                break
            except ValueError:
                print('Invalid input, please try again')
    return resp

CodePudding user response:

For the expected integer input, you don't need to use the try-except block. Use isdecimal() string method instead:

while True:
    age = input("Enter your age: ").strip()
    if age.startswith("-") or not age.isdecimal() or int(age) == 0:
        print("Invalid age. Must be a number greater than zero.")
        continue
    else:
        age = int(age)
        break

For the expected float input, use almost the same code:

while True:
    height = input("Enter your height in inches: ").strip()
    if height.startswith("-") or not height.replace(".", "", 1).isdecimal() \
           or float(height) == 0:
        print("Invalid height. Must be a number greater than zero.")
        continue
    else:
        height= float(height)
        break

The only difference (beside using float() instead of int()) is temporary removing a possible dot symbol (.) – but at most one such symbol – before applying the isdecimal() testing method:

      height.replace(".", "", 1).isdecimal()
            ^^^^^^^^^^^^^^^^^^^^  

From the String Methods in the Python Library Reference:

str.isdecimal()
Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U 0660, ARABIC- INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

See also What's the difference between str.isdigit(), isnumeric() and isdecimal() in Python?

  • Related