1

I am new to programming, and I am not sure how to figure this out.

I want to raise an error when an integer goes over the max integer ... so I imported sys ... The max integer is 2147483647 and the min is -2147483648. I am creating a list using the Fibonacci sequence so I tried to write some code that said:

if i > 2147483647:
    print "Overflow Error"

... and likewise for the minimum value. However, it does not do anything and I am still able to list numbers past 2147483647.

What am I doing wrong?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160
  • 7
    Please post the *complete* [example](http://sscce.org). This is just a print, which of course has no effect to the logic of the program. – phihag Feb 12 '13 at 22:49
  • 1
    Are you saying it's not crashing _and_ it's not printing your message? In that case, simply debug your code. – keyser Feb 12 '13 at 22:49
  • 2
    Python integers can be as large as memory allows, actually. Try it; `import sys; sys.maxint * 2`. – Martijn Pieters Feb 12 '13 at 22:51
  • "max int" only matters if you're working with the system's definition of a C int data type. (Using an operating system API, interacting with other libraries without good Python wrapper extensions, serializing/deserializing data, etc) – Jeremy Brown Feb 12 '13 at 23:00
  • I smelling a homework problem... – Paul Cezanne Feb 12 '13 at 23:07

2 Answers2

2

Python long integers have no upper limit, they are only limited to what you can fit in RAM:

>>> import sys
>>> sys.maxint * 2
18446744073709551614L

The sys.maxint value tells you where python will start to use the long type instead of int to represent integers; the transition is automatic.

You are not likely to hit that memory limit when calculating fibonacci sequences.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

As Martijn said, you won't hit any errors (unless you are dealing with VERY large numbers or lists of a very large size). However, Python doesn't allow you to actually use up all of your memory; it will raise an error if too much memory is used (MemoryError).

If you want to set a limit on your input, though:

from sys import maxint
if i > maxint: raise ValueError('i cannot exceed 2147483647')
elif i < -1 * maxint: raise ValueError('i must be greater than -2147483647').

I don't suggest you raise an OverflowError, ValueError is more appropriate.

I'm unclear on the question, so if you were trying to check if the list-size was greater than maxint:

from sys import maxint
if len(i) > maxint: raise ValueError('i cannot exceed 2147483647 elements')
# you don't need a minimum value, as the length cannot be negative

If you are trying to check if the max value of the list is greater than maxint:

from sys import maxint
if max(i) > maxint: raise ValueError('i cannot exceed 2147483647')
Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94