Search code examples
pythonif-statementtry-except

Can I add IF clause to TRY & EXCEPT clause


Please pardon me if I make any formatting issues here!

I am creating 2 variables, namely the mean and variance. Still working on the "variance" variable so please ignore that part.

Here's the background:

The mean and variance are int inputs. The mean can be of any value, on the other hand, the variance will need to be of value greater than 1. And whenever, the input prompts, and the users hit enter straightaway (without any inputs), the mean and variance will be 0 and 1 respectively.

I have attempted the question and want to integrate both the TRY & EXCEPT clause with the IF clause because to check of ValueError and to automatically stop the program if the users hit enter without any values...

I am not sure if this is doable, can anyone advise, please... Many thanks!

Here's my code:

mean = 0
variance = 1

valid_input = False
while valid_input == False:
    try:
        mean = int(input("Please enter the mean value: "))
        if mean == "":
            valid_input = True
            break
    except ValueError:
        print("Please enter a numeric value!")
    else:
        valid_input = True
print (mean, variance)

Solution

  • mean = 0
    variance = 1
    mean = input("Please enter the mean value: ")
    try:
        mean = int(mean)
        print (mean, variance)
    except ValueError:
        print("Please enter a numeric value!")
    

    This works. If the input is not an int, Please enter a numeric value is printed and the program exits.

    Or you can use the following code to determine if the user input is an integer, and if it is, you can convert it to int. You won't need the try-except block now. Ref

    import re
    # read value from keyboard
    value = input("Enter a string\n")
    # match the entered value to be a number
    result = re.match("[-+]?\d+$", value)
    # check if there was a match
    if result is not None:
        print("Entered string is an integer")
        print(int(value))
    else:
        # entered value contains letters also
        print("Entered string is not an integer")