[Edu-sig] problem with IF
john.zelle at wartburg.edu
Sat Jul 24 02:42:21 CEST 2004
Maybe this isn't really the forum, but I can't resist a couple quick
comments on this example.
Since this is a multiway decision (that is, 8 mutually exclusive
outcomes based on a single decision value), elif is definitely
appropriate but having two conditions on each clause is redundant and
often leads to errors. In fact there is an error in the code below,
since it can nver return 'N' (dirn can't be both >= 345 and < 22). Of
course, North is a bit of a special case; one way to do that is to split
"N" into its two cases:
if dirn < 22: return "N"
elif dirn < 77: return "NE"
elif dirn < 112: return "E"
elif dirn < 157: return "SE"
elif dirn < 345: return "NW"
else: return "N" # anything >= 345
Also, if one is getting an int as input, you may as well use the input
function (save raw_input for strings), then you won't accidently use a
string as an int.
dirn = input("Enter bearing in degrees: ")
Of course, if this were embedded in a GUI, chances are you would be
forced to get a string and do the conversion.
ps. I can't help thinking there may be a more elegant way of doing the
Rick Holbert wrote:
>I think you should check to see if the bearing is between two values as
> if dirn >= 345 and dirn < 22:
> return "N"
> elif dirn >= 22 and dirn < 77:
> return "NE"
> elif dirn >= 77 and dirn < 112:
> return "E"
> elif dirn >= 112 and dirn < 157:
> return "SE"
> elif dirn >= 157 and dirn < 202:
> return "S"
> elif dirn >= 202 and dirn < 247:
> return "SW"
> elif dirn >= 247 and dirn < 292:
> return "W"
> elif dirn >= 292 and dirn < 345:
> return "NW"
>inp = int(raw_input("Enter Bearing in degrees: "))
>dir = dirnPoint(inp)
>print "%d degrees is %s" % (inp, dir)
>On Thursday 22 July 2004 21:49, ken wrote:
>>I have been trying to write a program to display the reading from a
>>weather station. I was trying to change the direction of the wind from
>>degrees to points of compass. Have tried various if.. elif.. but it
>>seems to take the last option in the list regardless of the value of the
>Edu-sig mailing list
>Edu-sig at python.org
More information about the Edu-sig