Python Forum
try except issue - 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: try except issue (/thread-36465.html)

Pages: 1 2


try except issue - Frankduc - Feb-22-2022

Cant make it work.


must be indentation

TY


RE: try except issue - jefsummers - Feb-22-2022

Well, related to indentation, issue is likely scope. Add at line 6 val_L =0. See if that works.


RE: try except issue - deanhystad - Feb-22-2022

You really need to start using 4 space indentation, and use consistent indentation.

There is no exception handler to catch the ValueError here:
choix = int(input("Votre choix? "))
or here:
val_G = float(input("Entrez un volume en litres:  "))
Does choix need to be an integer? I would leave it a string and change the if statement.
if choix == '1':
...
elif choix == '2':
...
else:
If you aren't using input as an integer, why convert it to an integer? Converting user input adds a lot of extra code, and many chances for making errors.

val_L is not defined here because this is in the exception block that only executes if an error occurred converting input to a float and assigning to val_L:
        if val_L < 0:
            print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
        elif val_L > 100:
            print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
This is not an indenting error. It is a logic error. You need to think about all the pieces of the exception handler.
try:
    code that might raise a XXXError
except XXXError:
    code that repairs or cleans up the mess when XXXError occurs. Only executes if XXXError exception was raised.
else:
    code that only executes if XXXError exception was not raised
finally:
    code that executes no matter what.  Executes after the except block or the else block
You probably haven't read about the "finally" block yet. The "finally" block is where you put code that has to execute regardless of an exception being raised or not. This is an example from some code I've been working on.
    def set_index(self, index):
        """set_value using selection index"""
        if not self._locked:
            self._locked = True
            try:
                self.show_index(index)
                self.send_value()
            finally:
                self._locked = False
        return self
This code may raise an exception.
                self.show_index(index)
                self.send_value()
I don't even know which exceptions it might raise. Actually I don't even care if it raises an exception. I am fine with this code dumping a stack trace to stderr. However it is very important that I execute this code.
                self._locked = False
So I used a try/finally exception handler. Essentially it says "An exception might happen here. It is someone else's job to clean up. I only need to make sure that I set _locked = False."


RE: try except issue - BashBedlam - Feb-22-2022

If it were me, I wouldn't usetry/exceptat all. I would just test the user input for acceptable responses like this:
print('Choisir une conversion')
print("   1. Gallon américain")
print("   2. Litre")

choix = ''
while choix != '1' and choix != '2' :
	print("Choisir entre 1 et 2 svp")
	choix = input("Votre choix? ")
print("")

sortir = False
while sortir == False :
	if choix == '1' :
		répolnse = input("Entrez un volume en gallons:  ")
		if répolnse.isdigit () :
			sortir = float (répolnse) * 3.7854
			print  (f'{répolnse} gallons équivaut à {sortir} litres.')
	else :
		répolnse = input("Entrez un volume en litres:  ")
		if répolnse.isdigit () :
			sortir = float (répolnse) / 3.7854
			print (f'{répolnse} liters équivaut à {sortir} gallons.')
	if sortir == False :
		print(f"{répolnse} n'est pas un nombre, veuillez recommencer")
	if sortir < 0 or sortir > 100:
		print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
		sortir = False



RE: try except issue - Frankduc - Feb-22-2022

Hello all,

Thank you for your input. I solve it but lost time with indent. I wont get all the points for last question.
sucks! Try except not my forte.


RE: try except issue - deanhystad - Feb-22-2022

I like exceptions better than testing. When you start writing bigger code you quickly reach a point where you are writing more code to check for errors than you are writing code that does something useful. I would write FrancDuc's code like this:
try:
    choix = input("Choisir une conversion\n\t1. Gallon américain\n\t2. Litre\nVotre choix? ")
    print("")

    if choix not in ("1", "2"):
        raise ValueError("Choisir entre 1 et 2 svp")

    if choix == '1':
        try:
            gallons = float(input("Entrez un volume en gallons:  "))
        except ValueError:
            raise ValueError("allo n'est pas un nombre, veuillez recommencer")

        if gallons < 0:
            raise ValueError("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
        elif gallons > 100:
            raise ValueError("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")

        litres = gallons * 3.78
        print(gallons, 'gallons équivaut à ', litres, 'litres')

    elif choix == '2':
        try:
            litres = float(input("Entrez un volume en litres:  "))
        except ValueError:
            raise ValueError("allo n'est pas un nombre, veuillez recommencer")
        gallons = litres / 3.78
        print(litres, 'litres équivaut à ', gallons, 'gallons')

except ValueError as msg:
    print(msg)
All the exception recoveries are the same in this code. Print a message and exit. If I wanted to test everything instead of using exceptions this would be very difficult to do. I suppose I could use sys.exit() to jump out of the script.
import sys

choix = input("Choisir une conversion\n\t1. Gallon américain\n\t2. Litre\nVotre choix? ")
print("")

if choix not in ("1", "2"):
    print("Choisir entre 1 et 2 svp")
    sys.exit()

if choix == '1':
    try:
        gallons = float(input("Entrez un volume en gallons:  "))
    except ValueError:
        print("allo n'est pas un nombre, veuillez recommencer")
        sys.exit()

    if gallons < 0:
        print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
        sys.exit()
    elif gallons > 100:
        print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
        sys.exit

    litres = gallons * 3.78
    print(gallons, 'gallons équivaut à ', litres, 'litres')

elif choix == '2':
    try:
        litres = float(input("Entrez un volume en litres:  "))
    except ValueError:
        print("allo n'est pas un nombre, veuillez recommencer")
        sys.exit()
    gallons = litres / 3.78
    print(litres, 'litres équivaut à ', gallons, 'gallons')
But that is really ugly and I still have exception handlers for doing the float conversion. isdigit() is not an adequate test for checking if a str can be converted to a float number. I could use a regular expression, but those are really confusing and easy to get wrong.

What if BashBedlam is right and the code should not exit until it has received correct input? Can you do that with try/except?
def get_volume():
    choix = input("Choisir une conversion\n\t1. Gallon américain\n\t2. Litre\nVotre choix? ")
    print("")

    if choix not in ("1", "2"):
        raise ValueError("Choisir entre 1 et 2 svp")

    if choix == '1':
        try:
            gallons = float(input("Entrez un volume en gallons:  "))
        except ValueError:
            raise ValueError("allo n'est pas un nombre, veuillez recommencer")

        if gallons < 0:
            raise ValueError("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
        elif gallons > 100:
            raise ValueError("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
        litres = gallons * 3.78

    elif choix == '2':
        try:
            litres = float(input("Entrez un volume en litres:  "))
        except ValueError:
            raise ValueError("allo n'est pas un nombre, veuillez recommencer")
        gallons = litres / 3.78
    return gallons, litres

while True:
    try:
        gallons, litres = get_volume()
    except ValueError as msg:
        print(msg)
    else:
        print(gallons, 'gallons équivaut à ', litres, 'litres')
        break



RE: try except issue - BashBedlam - Feb-22-2022

(Feb-22-2022, 11:14 PM)deanhystad Wrote: What if BashBedlam is right



RE: try except issue - Frankduc - Feb-23-2022

Here's what i gave for Question 5 to the exam.

print('Choisir une conversion')
print("   1. Gallon américain")
print("   2. Litre")
try:
 choix = int(input("Votre choix? "))
 print("")

 if (choix == 1):

  try:
   val_L = float(input("Entrez un volume en gallons:  "))

  except:
     print("allo n'est pas un nombre, veuillez recommencer")

  else:

    if (val_L < 0):
       print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
    elif (val_L > 100):
       print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
    else:
     r = val_L * 3.78
     print(val_L, 'gallons équivaut à ', r, 'litres')

 elif (choix == 2):

  try:
    val_G = float(input("Entrez un volume en litres:  "))

  except:
     print("allo n'est pas un nombre, veuillez recommencer")

  else:

    if (val_G < 0):
       print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
    elif (val_G > 100):
       print("Entrez une valeur comprise entre 0 et 100, veuillez recommencer ")
    else:
     r = val_G / 3.78
     print(val_G, 'litres équivaut à ', r, 'gallons')

 else:
    print("Choisir entre 1 et 2 svp")
except:
    print("Choisir entre 1 et 2 svp")
But my first try wont work if user enter 'blabla'. I spent to much time on indenting. Good thing it was the last question. 25pts i will certainly lose 5 pts on that.


RE: try except issue - BashBedlam - Feb-23-2022

se la vie Wink


RE: try except issue - Gribouillis - Feb-23-2022

That's where I like to write specialized input functions
def input_choice(msg, choices, err='Error: invalid choice, try again.'):
    while True:
        v = input(msg).strip()
        if v not in choices:
            print(err)
            continue
        return v

def input_float(msg, min=..., max=...,
                err='Error: a number is required, try again.'):
    while True:
        try:
            v = float(input(msg))
        except ValueError:
            print(err)
            continue
        else:
            if min != ... and v < min:
                print(f'Error: a value larger than {min} is required, try again.')
                continue
            if max != ... and v > max:
                print(f'Error: a value smaller than {max} is required, try again.')
                continue
            return v

print("""\
Choisir une conversion
    1. Gallon américain
    2. Litre""")
c = input_choice('Votre choix (1, 2) ? ', ('1', '2'))

if int(c) == 1:
    val_L = input_float(
        'Entrez un volume en gallons (0 - 100): ', min=0, max=100)
    ...