Home > front end >  Need to print out error messages for improper input; validation
Need to print out error messages for improper input; validation

Time:04-27

I'm writing a python script where I find the average of the sum of three numbers. I am using arguments for inputting the numbers. I need to finish the script by printing out error messages. If I enter something like:

  • avg3 3 5

  • avg3 3 4 5 6

  • avg3 3 one 5

it needs to print an error telling me how to use it.

Here is the start of the script:

def main():
    num1 = int(sys.argv[1])
    num2 = int(sys.argv[2])
    num3 = int(sys.argv[3])
    avg = (num1   num2   num3)/3
    print("The average of "  str(num1)   " "   str(num2)   " "   str(num3)   " "   "is "   str(round(avg,2)))

CodePudding user response:

If you are talking about catching the one arg as an error, you could simply catch a value error.

def main():
    try:
        num1 = int(sys.argv[1])
        num2 = int(sys.argv[2])
        num3 = int(sys.argv[3])
        avg = (num1   num2   num3)/3
        print("The average of "  str(num1)   " "   str(num2)   " "   str(num3)   " "   "is "   str(round(avg,2)))
    except ValueError:
        print("All your values need to be ints")

This will ensure that anything outside of a number being passed in as an arg would result in the message All your values need to be ints.

This won't catch any other errors, so you will have to catch them separately. For instance, your first example where you only pass 2 values won't work since there is no num3, but I'm assuming that isn't what you are asking about here.

CodePudding user response:

Edit:

For checking forcing an input of 3 numbers, and error checking:

def main():
    
    if len(sys.argv) != 4:
        print("You did not enter the correct amount of arguments")
    else:
        try:
            num1 = int(sys.argv[1])
            num2 = int(sys.argv[2])
            num3 = int(sys.argv[3])
            avg = (num1   num2   num3)/3

            print(f"The average of {num1} {num2} {num3} is {round(avg, 2)}")

        except (UnboundLocalError, IndexError) as e:
            # When you don't pass any args
            print("You need to pass arguments")
            print(f"($ python avg.py 3 1 2)\n Error = {e}")
        except ValueError as e:
            # You need to use numbers
            print(f"You need to pass arguments as ints")
            print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")
            print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")

See the below for explanation:


len(sys.argv) will be 4 when there are 3 arguments (try print(sys.argv) for exploring this)

You could use a try statement to catch and except two common exceptions when passing args:

def main():
    try:
        num1 = int(sys.argv[1])
        num2 = int(sys.argv[2])
        num3 = int(sys.argv[3])
        avg = (num1   num2   num3)/3

        print(f"The average of {num1} {num2} {num3} is {round(avg, 2)}")

    except (UnboundLocalError, IndexError) as e:
        # When you don't pass any args
        print("You need to pass arguments")
        print(f"($ python avg.py 3 1 2)\n Error = {e}")
    except ValueError as e:
        # You need to use numbers
        print(f"You need to pass arguments as ints")
        print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")

try will run a block, and except will run when it's listed exceptions are met in the try block (exiting the try loop).


You could also simplify your code to:

nums = [int(x) for x in sys.argv[1:4]]
avg = sum(nums)/3

And access your numbers with

# Same as nums1
nums[0] 

and change the length of incoming arguments to anything >= 1 (if you want):

def main():
    try:

        nums = [int(x) for x in sys.argv[1:len(sys.argv)]]
        avg = sum(nums)/len(nums)

        print(f"The average of {', '.join([str(x) for x in nums])} is {round(avg, 2)}")

    except (UnboundLocalError, IndexError, ZeroDivisionError) as e:
        # When you don't pass any args
        print("You need to pass arguments")
        print(f"($ python avg.py 3 1 2)\n Error = {e}")
    except ValueError as e:
        # You need to use numbers
        print(f"You need to pass arguments as ints")
        print(f"(1 or 432. not 1.2, 324.0)\n Error = {e}")
  • Related