Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python, exceptions
#1
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!
Reply
#2
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.
Reply
#3
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?
Reply
#4
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)
Reply
#5
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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#6
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?
Reply
#7
(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.
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Split string between two different delimiters, with exceptions DreamingInsanity 2 353 Aug-24-2020, 08:23 AM
Last Post: DreamingInsanity
  handling 2 exceptions at once Skaperen 2 468 Jun-27-2020, 08:55 AM
Last Post: Yoriz
  remove spaces with exceptions catosp 4 483 May-29-2020, 09:32 AM
Last Post: catosp
  Looking for advice and Guidance on Exceptions used within Functions paul41 1 450 Nov-14-2019, 12:33 AM
Last Post: Larz60+
  multi-line messages in raised exceptions? Skaperen 3 1,355 Aug-01-2019, 02:17 AM
Last Post: Skaperen
  Change linenumber and filename printed in exceptions like #line in C kryptomatrix 2 710 Jul-12-2019, 06:01 AM
Last Post: Gribouillis
  Creating custom exceptions that co-operate LadySvetlana 4 872 Mar-19-2019, 04:24 PM
Last Post: LadySvetlana
  Catching exceptions in embedded code no longer works on 3.7.2? FFMG 5 900 Feb-02-2019, 10:15 AM
Last Post: Larz60+
  Problems with not having exceptions crash my script league55 7 1,693 Feb-16-2018, 09:06 PM
Last Post: DeaD_EyE
  raising multiple exceptions Skaperen 10 4,311 Mar-19-2017, 06:32 AM
Last Post: wavic

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020