[Tutor] redundant code

Magnus Lyckå magnus@thinkware.se
Sat May 10 14:21:33 2003


At 21:00 2003-05-09 -0700, Greg Chapman wrote:
>from random import randrange
>from sys import exit
>from string import lower

This is redundant. Since Python 1.6 (?) you can use "again.lower()"
instead of "string.lower(again)".

>def question():
>      n1 = randrange(1, 10)
>      n2 = randrange(1, 10)
>      answer = int(raw_input('How much is %d times %d? ' % (n1, n2)))
>      if answer != n1 * n2:
>          return 1
>      else:
>          return 0

This is not the function Peter asked for. You don't let the user
answer the same questions several times.

But in general Gregs "while 1: ... break" loop is a common
Python approach when you have to go through a loop at least
once, but there are options...

Refering to Peter's code:
It's a bit odd that you put the "No. Try again" and "Yes,
that is correct" replies in different parts of the code, isn't it?
They are a pair, and it's probably better to keep them together,
both to make the code easy to understand, and to reduce the risk
that we miss something if we have to change the code.

raw_input returns a string, so str(raw_input()) is redundant.

Untested code follows...

from random import randrange
# from sys import exit #Why exit? A program exits when it reaches its end.
def question():
     n1 = randrange(1, 10)
     n2 = randrange(1, 10)
     continue = True
    while continue:
         answer = int(raw_input('How much is %d times %d? ' % (n1, n2)))
         if answer == n1 * n2:
             print "Yes, that is correct."
             continue = False # Alternative: Use "while 1:" above, and 
"break" here.
         else:
            print "No. Try again."

def main():
     while 1:
         question()
         yesNo = raw_input("Would you like another question (type Y or N)?")
         if yesNo.lower() != 'y':
             break

if __name__ == '__main__':
     main()

The last is a common idiom which makes it possible to use this
code both as a standalone program, and as a module used by other
programs.


--
Magnus Lycka (It's really Lyckå), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program