[Tutor] logic ?

Ignacio Vazquez-Abrams ignacio@openservices.net
Thu, 4 Oct 2001 17:30:48 -0400 (EDT)


On Thu, 4 Oct 2001, Jerry Lake wrote:

> for some reason, I can't get this to function
> properly, if someone can point me in the right
> direction, I'd appreciate it. the problem comes
> in at the if/else in the slope formula, it returns
> all slopes as 0.
>
> <snip>
> #!/usr/bin/python2
>
> import math
>
> x1 = input("Enter a coordinate for x1: ")
> y1 = input("Enter a coordinate for y1: ")
> x2 = input("Enter a coordinate for x2: ")
> y2 = input("Enter a coordinate for y2: ")
>
> def distance(x1, y1, x2, y2):
>    dx = x2 - x1
>    dy = y2 - y1
>    dsquared = dx**2 + dy**2
>    result = math.sqrt(dsquared)
>    return result
>
> def slope(x1, y1, x2, y2):
>    x = x1 - x2
>    y = y1 - y2
>    if (x or y == 0):
>       slope = 0
>    else:
>       slope = x / y
>    return slope
>
> print "The distance between the points is", distance(x1, y1, x2, y2)
> print "The slope of the two points is ", slope(x1, y1, x2, y2)
>
> </snip>

There are three problems:

1) input() evaluates the inputted text, leading to a security hole. Use
raw_input() instead and convert the input to a float.

2) Your condition in the if statement is wrong. it should read "x==0 or y==0",
although "y==0", or even just "y" will do for this exercise.

3) By default, the "/" operator does integer division if both operands are
integers. You need to use float() to convert them to floats.

-- 
Ignacio Vazquez-Abrams  <ignacio@openservices.net>