Python Forum
Python, exceptions - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Python, exceptions (/thread-30956.html)



Python, exceptions - KingKhan248 - Nov-15-2020

I'm trying to practice using exceptions in python programming but I can't seem to figure out how it works.
I'm trying to create a basic program that asks the user to enter the side lengths of a triangle and then calculates and outputs the perimeter. I want to use exceptions to give error messages when any of the side lengths are entered incorrectly, like if instead of a number they enter "akjdhg", and it should give an error when they enter a negative number.

try:
    len1 = (float(input("Enter the length of one side of the triangle: ")))
    len2 = float(input("Enter the length of a different side: "))
    len3 = float(input("Enter the length of the final side: "))

except ValueError:
    print("Please enter a number.")
except:
    if len1 <= 0 or len2 <= 0 or len3 <= 0:
    
        print("Please enter a positive number.")
When I enter anything other than a number I do get the error message I want but when I enter a negative or 0, the error message does not appear and the code continues.

Still pretty new to this forum I hope I followed all the rules and guidelines on posting here. If not please let me know and I will fix it. Thanks in advance!


RE: Python, exceptions - ndc85430 - Nov-15-2020

Of course you don't see the error when negative values are entered, because the function float doesn't raise an exception in that case (because those are valid of course). You could either put the check in the try block or, I believe an else block.


RE: Python, exceptions - KingKhan248 - Nov-15-2020

So if I change my data type it should work? I thought the if statement in the second exception would work, why doesn't it?


RE: Python, exceptions - deanhystad - Nov-15-2020

You should raise an exception. I use this pattern when I need user input.
def get_input(prompt, validate = None):
    value = input(prompt)
    if validate:
        value = validate(value)
    return value;

def positive_float(value):
    value = float(value)
    if value < 0.0:
        raise(ValueError('Value must be positive number'))
    return value;

try:
    l = [get_input('Enter triangle leg: ', positive_float) for _ in range(3)]
except Exception as msg:
    print(msg)



RE: Python, exceptions - buran - Nov-15-2020

Looking at your code I think you misunderstand how the try/except works. When there is error in the try block it looks at the exceptions. You handle ValueError and you also have all-catching blank except`. When you enter a negative number, no exception is raised so no except block is entered.

Probably you want to have else part. It will run after the try block if no except` block was entered
try:
    len1 = (float(input("Enter the length of one side of the triangle: ")))
    len2 = float(input("Enter the length of a different side: "))
    len3 = float(input("Enter the length of the final side: "))
 
except ValueError:
    print("Please enter a number.")
else:
    if len1 <= 0 or len2 <= 0 or len3 <= 0:
     
        print("Please enter a positive number.")
Note that it will print the message and just continue with program execution.
For completeness you should know there can be also finally - i.e. this code will be executed always, regardless of except part being executed or not.


RE: Python, exceptions - KingKhan248 - Nov-15-2020

That makes sense @buran. The problem is, I want this program to terminate as soon as they enter in a negative number or 0. If I use the else statement, wouldn't the program ask the user to input values even after a negative number was entered? If for len1 they entered -15 wouldn't the program then ask for len2 and len3, then at the end output the error message?


RE: Python, exceptions - buran - Nov-15-2020

(Nov-15-2020, 06:44 AM)KingKhan248 Wrote: If I use the else statement, wouldn't the program ask the user to input values even after a negative number was entered? If for len1 they entered -15 wouldn't the program then ask for len2 and len3, then at the end output the error message?
Yes it will ask for all 3 and then it will check for negative values. @deanhystad showed you one possible approach how to check for negative number immidiatelly. One thing that he does not show is how to keep asking for input until you don't get valid input. But also in his case it will not terminate immediately. It will continue to collect rest values.