Try/Except Syntax Error Help


#1

I can’t determine the problem with this code. I don’t know much about how try and except work. The error is on the word except.

def testiffloat(part):
    if str(part) == part:
      try:
        part = float(raw_input('Leg %i' % (part))
      except ValueError:
        return False
    else:
      return True

#2

Not sure I follow why this function would take any input other than the parameter. It’s a simple utility to return True or False depending whether the input parameter is a float or not.

try:
    return part % 1 != 0
except TypeError:
    return "Input Error!"

The purpose behind using TRY-EXCEPT is to trap exceptions and handle them ourselves. We assume the inputs are valid and write an expression that will raise an exception if they are not. Above, % can only be applied to numbers so will raise an exception on string input, or other non-numeric values.

The above is not a solution, just a demo of how to use TRY.


#3

Do you know why there’s a syntax error on except for me?


#4

What is the Trace message?


#5

What do you mean? Do you want just the entire code? btw I’m trying to write a triangle solver.

import math

def testiffloat(part):
    if str(part) == part:
      try:
        part = float(raw_input('Leg %i' % (part))
      except ValueError:
        return False
    else:
      return True

sidea = "red"
sideb = "blue"
hyp = "green"

while testiffloat(sidea) == False:
  sidea = raw_input("Leg A: ")

while testiffloat(sideb) == False:
  sideb = raw_input("Leg B: ")
  
while testiffloat(sidehyp):
  sidehyp = raw_input("Hyp: ")

while sidehyp < sidea or sidehyp < sideb:
  print "Hyp is too small."
  sidehyp = float(raw_input("Hyp: "))
test_hyp(sidehyp)

#6

This is an example of a traceback message…

Traceback (most recent call last):
  File "<pyshell#274>", line 1, in <module>
    'two' % 1 != 0
TypeError: not all arguments converted during string formatting

Why is it important to test for floats?


#7

I didn’t get a message like that. I just want to cover string inputs.


#8

Okay, so the TRY expression should just convert the inputs to a float.

try:
    return float(part)
except ValueError:
    return "Input Error!"

The above will convert, '5' to 5.0, but will raise an exception on 'five'.

>>> float('5')
5.0
>>> float('five')
Traceback (most recent call last):
  File "<pyshell#287>", line 1, in <module>
    float('five')
ValueError: could not convert string to float: 'five'
>>> 

This function should not take both a parameter and raw_input. Work with only the parameter in the function.

Note:

The terms to describe parts of a triangle are,

side
vertex
height (think amplitude or range)
base (think domain)
hypotenuse
area
perimeter
angle
sine
cosine
tangent

and so on… Notice that ‘part’ is not among them. Names we use in math programs should describe their concepts, and not be plain generic terms; i.e., not ‘part’, etc.

Your program should combine functions into a single one where inputs are concerned, and likewise where computing is concerned. You can use one function to get all the sides.

>>> def get_side(name):
    try:
        side = float(input("Side %s: " % name))
        if side > 0: return side
        else: raise ValueError
    except ValueError:
        get_side(name)

        
>>> get_side('a')
Side a: five
Side a: -5
Side a: 0
Side a: 5
>>> 

and one for all angles,

>>> def get_angle(name):
    try:
        angle = float(input("Angle %s: " % name))
        if 0 < angle < 180: return angle
        else: raise ValueError
    except ValueError:
        get_angle(name)

        
>>> get_angle("A")
Angle A: 0
Angle A: 180
Angle A: 90
>>> 

This is how to approach your overall design. Make it functional by defining expectations and then writing to meet them with the least amount of code.


#9

Ok but why do I get a syntax error on the word except?


#10

Thank you for the help!


#11

The error may be on the line before that. The ^ only indicates where parsing terminated, not where the error is, exactly.


#12
>>> def check_angles(x):    # x is a tuple
	return sum(x) == 180

>>> A = get_angle('A')
Angle A: 30
>>> B = get_angle('B')
Angle B: 60
>>> C = get_angle('C')
Angle C: 90
>>> check_angles((A, B, C))
True
>>> 
>>> def check_sides(x):    # x is a list
	return sum(sorted(x)[:2]) > sorted(x)[2]

>>> check_sides([50,40,30])
True
>>> 

Edit:



>>> def mismatch(name):
	return '%s mismatch error' % name

>>> def check_angles(x):
	return sum(x) == 180 if len(x) == 3 else mismatch('Angle')

>>> def check_sides(x):
	return sum(sorted(x)[:2]) > sorted(x)[2] if len(x) == 3 else mismatch('Side')

>>> check_angles((30, 40, 50, 60))
'Angle mismatch error'
>>> check_sides([50,40])
'Side mismatch error'
>>> 

Above we cannot depend upon a loop construct and must respond and move on. This is a case for an exception, though, unless it is human inputs we’re dealing with. Program inputs should always raise exceptions, and not the kind we can smooth away with TRY-EXCEPT.


#13
>>> def mismatch(name, given):
    return '%s mismatch error: %d arguments given, 3 expected' % (name, given)

>>> def check_angles(x):
    return sum(x) == 180 if len(x) == 3 else mismatch('Angle', len(x))

>>> def check_sides(x):
    return sum(sorted(x)[:2]) > sorted(x)[2] if len(x) == 3 else mismatch('Side', len(x))

>>> check_angles((30, 40, 50, 60))
'Angle mismatch error: 4 arguments given, 3 expected'
>>> check_sides([50,40])
'Side mismatch error: 2 arguments given, 3 expected'
>>> 

We get around whether the argument is a tuple or a list by using the splat parameter. It lets the function accept all arguments in the call, regardless their number, as a package which we can treat as a list or a tuple.

>>> def check_angles(*x):
    return sum(x) == 180 if len(x) == 3 else mismatch('Angle', len(x))

>>> def check_sides(*x):
    return sum(sorted(x)[:2]) > sorted(x)[2] if len(x) == 3 else mismatch('Side', len(x))

>>> check_angles(30, 40, 50, 60)
'Angle mismatch error: 4 arguments given, 3 expected'
>>> check_sides(50,40)
'Side mismatch error: 2 arguments given, 3 expected'
>>>