Python Forum
Try except how is it working?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try except how is it working?
#1
I am trying to make it work. The code ask for 3 values and return the highest value.
If input is a string. I want to handle the error with an exception.

print("Tapez trois valeurs numériques entières:")

val1 = int(input("Entrez première valeur:  "))
val2 = int(input("Entrez deuxième valeur:  "))
val3 = int(input("Entrez troisième valeur:  "))
try:
 if (val1 > val2 and val1 > val3):
    print(val1)
 elif (val2 > val3):
    print(val2)
 else:
    print(val3)
except:
    print(merde)
Error:
Tapez trois valeurs numériques entières: Entrez première valeur: > l Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'l' is not defined >
Reply
#2
try:
    val1 = int(input('First Value:\n>> '))
    val2 = int(input('Second Value:\n>> '))
    val3 = int(input('Third Value:\n>> '))

    if val1 > val2 > val3:
        print(f'Value 1 is greater  {val1}')
    elif val2 > val3:
        print(f'Value 2 is greater {val2}')
    else:
        print(f'Value 3 is greater {val3}')
except ValueError:
    print('Enter only whole numbers')
Output:
First Value: >> pop Enter only whole numbers
BashBedlam likes this post
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
What am i doing wrong?

Whats the difference between my code and yours:

print("Tapez trois valeurs numériques entières:")
try:
    val1 = int(input("Entrez première valeur:  "))
    val2 = int(input("Entrez deuxième valeur:  "))
    val3 = int(input("Entrez troisième valeur:  "))

    if (val1 > val2 and val1 > val3):
         print(val1)
    elif (val2 > val3):
         print(val2)
    else:
         print(val3)
except ValueError:
     print(merde)
Thank you
I got it sorry! Thank you very much
Reply
#4
try/except doesn't do much for code that cannot raise an exception. You should also limit the code between try/except to the code you think might generate an error. the print() commands are not going to raise a ValueError, so they probably should be outside the try/except block.
try:
    val1 = int(input('First Value:\n>> '))
    val2 = int(input('Second Value:\n>> '))
    val3 = int(input('Third Value:\n>> '))
except ValueError:
    print('Enter only whole numbers') 
else:
    if val1 > val2 > val3
        print(f'Value 1 is greater  {val1}')
    elif val2 > val3:
        print(f'Value 2 is greater {val2}')
    else:
        print(f'Value 3 is greater {val3}
For something like this you should use a collection instead of individual variables. This code takes 3 inputs and prints the max value. The only purpose for val1, val2 and val3 is to hold integer values so they can be compared. This is easier done putting the values in a list where you can use functions like max() and index().
try:
    values = [int(input(f"{prompt} Value:\n>>")) for prompt in ("First", "Second", "Third")]
except ValueError:
    print('Enter only whole numbers')
else:
    max_value = max(values)
    max_index = values.index(max_value)
    print(f"Value {max_index+1} is greater {max_value}")
If you don't like list comprehensions (yet) you can do the loop yourself. Here I only retain the max value.
max_value = max_index =  None
try:
    for index, prompt in enumerate(("First", "Second", "Third")):
        value = int(input(f"{prompt} Value:\n>>"))
        if max_value is None or value > max_value:
            max_index, max_value = index, value
except ValueError:
    print('Enter only whole numbers')
else:
    print(f"Value {max_index+1} is greater {max_value}")
8 lines instead of 13 is not a big reduction in code, but it is 5 fewer lines that can contain an error. More importantly the loop code treats input processing generically. val2 does not require any special code. If the input code works for val1, it will work for val2 and val3 and valN.
Frankduc likes this post
Reply
#5
Very good and interesting.
Thank you Dean
Wish you were my teacher
Reply
#6
And if you don't like the loop you could do this:
print("Tapez trois valeurs numériques entières:")
try:
    values = (
        int(input("Entrez première valeur:  ")),
        int(input("Entrez deuxième valeur:  ")),
        int(input("Entrez troisième valeur:  "))
    )
except ValueError:
    print("merde")
else:
    print(max(values))
One thing I forgot to mention. Hopefully you noticed it in menator's post. You should always specify the exception type(s) you are going to process. Your program should expect some user to enter something that is not an integer. It should not be expecting a NameError or an AttributeError. The exception handler should only catch ValueError exceptions, it should not catch all exceptions. If I run the program above and type ctrl+c, I get a Keyboard interrupt, a type of exception that is not caught by the exception handler. If I remove the "ValueError" the code catches (most) all exceptions. Now if I type crl+c the program prints prints "merde".

Printing "merde" when I type ctrl+c is not what I expect. I am sorry but I decided I didn't need to use a program to find the max number in 1, 2, 3. I figured it out all by myself and all I wanted to do was quit out of the program by typing ctrl+c. But instead of quitting, your program swore at me. Thanks a lot pal!

In this case capturing all the exceptions isn't too bad. The program quickly exits either way. I have seen some poorly defined exception handling that makes it quite difficult to see when a real error occurs. And some of this code can make it difficult for your program to terminate. Run the program and try to exit out of the loop without entering three numbers.
print("Tapez trois valeurs numériques entières:")
values = []
while len(values) < 3:
    try:
        values.append(int(input("Enter number: ")))
    except:
        print("Please enter an integer number")
print(max(values))
Frankduc likes this post
Reply
#7
Practical, in the second version the program still runs even if a wrong input is givin. The exam is this afternoon and its brute force approach. I cannot use methods that are not in chap 1 to 4. So no append, no max and certainly no enumerate. Try, except was my weakness this is good info.
The bid idea is to use the Try specifically where you know it can return an error, the rest end up in else. Except only return the error message you want to put in.
This option remain the best for the exam:

print("Tapez trois valeurs numériques entières:")
try:
    val1 = int(input("Entrez première valeur:  "))
    val2 = int(input("Entrez deuxième valeur:  "))
    val3 = int(input("Entrez troisième valeur:  "))
except ValueError:
    print('Enter only whole numbers') 
else:
    if val1 > val2 > val3:
        print('Value 1 is greater ',val1)
    elif val2 > val3:
        print('Value 2 is greater,', val2)
    else:
        print('Value 3 is greater ',val3)
I put 'merde' out of frustration. Big Grin

Edit: i forgot to ask what about sys.exit() and import system? When do i need it?

Thank you sir!
Reply


Forum Jump:

User Panel Messages

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