Simple script crashes IDLE

David Goodger goodger at users.sourceforge.net
Sun Sep 1 00:33:32 CEST 2002


davbucko wrote:
> But when all is "well", it crashes the machine.

What does "crashes" mean here?  Show us the output you see.  Usually,
you'll see an error traceback, which should lead you to the cause.

A "crash" is a much more serious incident, such as a core dump, or
blue screen, or a machine restart.  That's quite rare, but you may be
getting one, because you've got an infinite loop and you're running
out of memory.

> What have I done wrong?

You have some program logic errors.

> class Powers:
> 
>   def __init__(self):
>     self.list = {}

It's a dictionary (commonly called a "dict"), not a list.  Misleading.

>     for i in [2,3]:
>       self.list = {i: self.getThreeDigitPowers(i)} #Oh yeah, are you allowed
> to do this?

Yes, you're *allowed*, but you shouldn't want to.  What you're doing
is this: run getThreeDigitPowers on 2, store the list returned in a
dictionary, then run it on 3, and store the new list in a new
dictionary.  That last step throws away the last dictionary, by the
way.  But you'll never get there, because of the logic bug below.

What you want to do is this:

    self.list[i] = self.getThreeDigitPowers(i)

>   def getThreeDigitPowers(self,power):
>     number = 0
>     i = 1
>     powerlist = []
>     while number < 1000:
>       number = i**power
>       powerlist.append(number)
>     del powerlist[-1]
>     return powerlist
> #End of class

I assume what you want is a list of 0...999 raised to a power.  That's
not what you've asked for.

You're never increasing "number", which means the loop will never end.
 "powerlist" will grow forever, or until Python runs out of memory,
whichever comes first.  You guess which. ;-)

Why are you throwing away 999**power?  If you don't want it, say
"while number < 999" and don't calculate it at all.  In any case,
here's the function rewritten more Pythonically:

    powerlist = []
    for i in range(1000):
        powerlist.append(i**power)
    return powerlist

Or, if you're using a recent version of Python, just do this:

    return [i**power for i in range(1000)]

> a = Powers()
> 
> print "Number of Squares under 1000: ",len(a.list[2])
> print "List of Squares: \n"
> for i in a.list[2]:
>   print i
> print "\nNumber of Cubes under 1000: ",len(a.list[3])
> print "List of Cubes: \n"
> for i in a.list[3]:
>   print i
> 
> #End of file

The rest should work, but you should know that the Python standard is
is 4 spaces per indentation level, no tabs.

-- 
David Goodger  <goodger at users.sourceforge.net>  Open-source projects:
  - Python Docutils: http://docutils.sourceforge.net/
    (includes reStructuredText: http://docutils.sf.net/rst.html)
  - The Go Tools Project: http://gotools.sourceforge.net/




More information about the Python-list mailing list