Python Forum

Full Version: Syntax error not understood
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, 

Completely new user for Python coding. Please help to understand the error. 

import math 

def euclideanDistance(instance1,instance2, length):
    distance = 0
    for x in range(length):
        distance += pow((instance1[x]-instance2[x],2)
        return math.sqrt(distance)
it displays the following error 

Error:
File "test6.py", line 9     return math.sqrt(distance)          ^ SyntaxError: invalid syntax

please ignore the thread it was just a syntax error

distance += pow((instance1[x]-instance2[x],2))
When you get a syntax error like this the problem is often in the previous line.
You forgot a parenthesis.
Also, for integer powers, you can use the '**' operator:
distance += (instance1[x]-instance2[x])**2 
slightly off-topic but it seems the ** operator isn't limited to integers, for either exponent or mantissa, which would allow one to change the code to not import math and simply raise the distance to the power of 1/2

>>> 9**0.5
3.0
(Jan-03-2017, 12:57 PM)pedros Wrote: [ -> ]slightly off-topic but it seems the ** operator isn't limited to integers, for either exponent or mantissa, which would allow one to change the code to not import math and simply raise the distance to the power of 1/2

>>> 9**0.5
3.0

math.sqrt() may have some optimizations... and a good compiler could replace the operation with inlined multiplications when the exponent of '**' is a small integer constant.
One thing that was not mentioned. Your return statement is part of the loop.
That means you will never see a second iteration, thus negating the purpose of the loop