if else python

Thomas 'PointedEars' Lahn PointedEars at web.de
Wed Nov 25 06:10:09 EST 2015


Scott Montreuil wrote:

> I have an if statement which seems to run both commands and I cannot
> figure out why. (just learning so I may be missing something obvious) Any
> ideas?

Use a Python IDE and debugger.  I recommend PyDev, but YMMV.

> while True:
>         global latit,longt,jlatit,jlongt,mlongt,mlatit

Why globals?  Why so many?

>         response = urllib.urlopen(url)
>         data = json.loads(response.read())
>         latit = data['Data'][0]['Latitude']
>         longt = data['Data'][0]['Longitude']

DRY.

        [latit, longt] = [data['Data'][0][key]
                          for key in ['Latitude', 'Longitude']]

There may be even more efficient ways.  Certainly the value of data['Data'] 
can be stored in a variable.

>         jlatit = data['Data'][1]['Latitude']
>         jlongt = data['Data'][1]['Longitude']
>         mlatit = data['Data'][2]['Latitude']
>         mlongt = data['Data'][2]['Longitude']

Shouts out for applying DRY.

[added line continuation escape]

>         for i in user1locat:
>                 if float(i[2]) <= float(latit) <= float(i[3]) and \
>                 float(i[4]) >= float(longt) >= float(i[5]):
>                         newlocation = int(i[1])
>                        screen.addstr(7, 40, "%s at %s" %(user1, i[0]))

["{0} at {1}".format(user1, i[0]) is recommended instead:

<https://docs.python.org/3/library/stdtypes.html#old-string-formatting>]

The indentation of the last quoted line is – as posted – one space to the 
left of that of the previous line.  That is a syntax error in Python as the 
“if” statement is 8 columns to the left instead.  Perhaps you have mixed 
tabs and spaces and that got lost while posting; in any case, this is not 
the original code, so all bets are off.

Also, 8 spaces per indentation level is too much; it certainly is too much 
to be posted to Usenet where there is a customary limit at the 80th column.
An indentation of 4 spaces per level is recommended for Python code.  If the 
code still extends beyond the 80th column, you should use a line 
continuation escape sequence if that is syntactically necessary (it is not 
in my suggestion above).

<https://www.python.org/dev/peps/pep-0008/#indentation>


-- 
PointedEars

Twitter: @PointedEars2
Please do not cc me. / Bitte keine Kopien per E-Mail.



More information about the Python-list mailing list