Question on if, while, for.... Figured it out..

Steve Holden sholden at holdenweb.com
Mon Feb 11 12:19:59 EST 2002


"Fred" <c at tech.usd253.org> wrote in message
news:e959e7b.0202110901.485da0b0 at posting.google.com...
> OK, I figured it out (one other way at least).

A few more observations interspersed with your (now much cleaner!) code...
>
> -------------------
>
> num = input("Enter the numerator: ")
> den = input("Enter the denominator: ")
> test = 0
>
> if num > den: #Test for improper fraction.
>     i = num/den #This will only return the whole part.
>     j = num%den #This will return only the remainder.
>
Rather than comment the usage of "i" and "j", why not just use "d" for
dividend and "r" for remainder? The idea behind being able to choose
variable names is to allow them to have some mnemonic significance.

>     if j != 0:

Here you know there's a remainder, and you know what the dividend is. If you
subtract the remainder from your original number then divide by the
dividend, this will be the whole part. So you can replace the loop below
(which only works for small numbers) by a simple computation. I'm leaving
this to you, since you like to work out your own solutions...

>         for i in range(9,0,-1):
>             if num%i == 0 and den%i ==0 and test != 1:
>                 a = j/i
>                 b = den/i
>                 print "You entered an improper fraction, simplified it
> is: %d %d/%d" % (i,a,b),
>                 test = 1

By the way, if you *do* want to use a loop, rather than maintaining a
variable that tells you when your loop has doen its work, you can just use
the "break" statement to terminate it. This would have saved you testing the
"test" variable above, which in turn would have saved you from having to
initialise it even further above.

>     else:
>         print "You entered an improper fraction, simplified it is: %d"
> % (i)
>
>
>
> else:
>     for i in range(9,0,-1):
>         if num%i == 0 and den%i ==0 and test != 1:
>             a = num/i
>             b = den/i
>             print "The fraction you entered is %d/%d in lowest terms."
> % (a,b),
>             test = 1
Since here you know that the remainder is zero, this would be the
appropriate place to work out the lowest common denominator.

lots-more-meat-in-this-problem-yet-ly y'rs  - steve
--
Consulting, training, speaking: http://www.holdenweb.com/
Author, Python Web Programming: http://pydish.holdenweb.com/pwp/

"This is Python.  We don't care much about theory, except where it
intersects with useful practice."  Aahz Maruch on c.l.py







More information about the Python-list mailing list