[Tutor] trouble with if

Alan Gauld alan.gauld at btinternet.com
Fri Oct 26 09:35:00 CEST 2007


"Bryan Fodness" <bryan.fodness at gmail.com> wrote

>I cannot get this to work either.

Brian, when you post please tell us exactly what does not work.
If there is an error message send the whole error there is a lot
of useful information in them. Otherwise we have to read your
code and guess what might be happening. We need both code
and error text. The easier you make it for the tutors the more
likely you are to get a response!

> woffaxis = 7
>
> if woffaxis != 0:
>     woaf_pos = input("What is Wedge Direction (N/A, Lateral, Towards 
> Heal,
> Towards Toe)?")

Use raw_input() and convert the result rather than input().
Especially when the input is a string anyhow. Otherwise
you are leaving yourself open to scurity breaches and even
accidental damage to your data due to mistyping. This is
because input() tries to interpret its value as a Python
expression. Thus if the user enters a string Pyhon tries to
evaluate that string. Unless the usser has put quotes
around their input it will probably fail. I suspect that is
your problem but without an error message I can't be sure.

> if woaf_pos == 'Towards Toe':
>     woffaxis = woffaxis
> elif woaf_pos == 'Towards Heal':
>     woffaxis = (woffaxis * -1)
> else:
>     woffaxis = 0

Incidentally, you could replace this set of if statements
with a dictionary lookup:

responses = {"Towards Toe": 1, "Towards Head": -1}
woffaxis *= responses.get(woaf_pos,0)

Another tip is that when comparing user input to a
string its usually better to have the master strings
as all uppercase or all lowercase and then convert
the input string to all lower case or all upper case
as appropriate, and then compare.

It reduces user frustration over simple typos.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list