FactorPad
Faster Learning Tutorials

Python int Reference: Syntax of Python integers with examples

Often the first object type beginners learn in Python is the integer. Here we dig a bit deeper.
  1. About - Review the purpose, rules and location of int.
  2. Assignment - Construct an integer object with examples.
  3. Function - Learn int function syntax with examples.
  4. Methods - See int syntax with parameter examples.
  5. Help - Find additional information locally.
Paul Alan Davis, CFA, December 3, 2018
Updated: December 3, 2018
Everything in Python is an object. Thinking that way from the beginning will pay dividends later. Keep reading.

Outline Back Next

~/ home  / tech  / python  / reference  / python int


A Guide to Working with Integers in Python

Beginner

Python Reference

This Python reference offers programmers a quick way to learn Python and also serves as a source for reminders.

While the version documented here is Python 3.5.3, most of this is suitable for other versions of Python 3. Check your version for details.

Outline

  1. About the Python int Data Type
    1. How to access the int data type
  2. Python int Assignment
    1. Syntax
    2. Examples
  3. The Python int Function
    1. Syntax
    2. Examples
  4. Python int Methods
    1. Syntax
    2. Examples
  5. Find Local Help on Python int

1. About the Python int Data Type

The int data type represents integers and is one of three basic numeric data types in Python.

Integers are whole numbers without a decimal point. They can be input with no sign, a positive sign, or a negative sign. There is no limit to the size of an integer except as limited by system memory.

Integers are immutable, which means they cannot be changed once constructed. To change an integer that has been assigned a name, you must reassign it.

The int() function is a type conversion function, so it can be used to convert floats and strings to integers.

a. How to access the int data type
  • Module name - builtins
  • How to import module - As a built-in, no import is necessary.
  • Explicit function call - __builtins__.int()

Here we assume the most basic import scenario without aliasing. See our reference document on importing modules for more.

2. Python int Assignment

Below is syntax for creating an integer object with assignment followed by examples.

a. Assignment syntax
Syntax
x = 5
Assignment will infer the data type as an integer if an integer literal is supplied. Integer literals can take the following forms.
  • decimal (0 to 9)
  • octal (0o3742)
  • hexadecimal (0x7E2)
  • binary (0b11111100010)
b. Assignment examples
Basic assignment

Here we assign numbers in integer, octal, hexadecimal and binary forms. Notice how they are entered in numeric form as opposed to strings.

>>> x = 2018 # integer >>> x 2018 >>> type(x) <class 'int'> >>> x = 0o3742 # octal >>> x 2018 >>> type(x) <class 'int'> >>> x = 0x7E2 # hexadecimal >>> x 2018 >>> type(x) <class 'int'> >>> x = 0b11111100010 # binary >>> x 2018 >>> type(x) <class 'int'>
Change a string to an int in Python with assignment

To change a string to an int assign a string in the format of an integer literal.

>>> x = int('5') # number as a string >>> x 5 >>> type(x) <class 'int'> >>> x = int('0b101') # binary >>> x 5 >>> x = int('five') # uninterpretable string Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: 'five' >>> x = int('+0005') # interpretable string with + sign >>> x 5

As you see in the last example, the leading zeros will be stripped from the string. Also, while the + sign is not required, Python will not throw an error.

Change a float to an int in Python with assignment

To change a float to an int assign a floating point number in a similar fashion. As earlier, a string structured like a float works, but uninterpretable strings do not.

>>> x = int(5.0) # a float >>> x 5 >>> type(x) <class 'int'> >>> x = int('5.0') # a float as a string >>> x 5 >>> x = int(5.9) # a float is not rounded >>> x 5 >>> x = int(round(5.9)) # a float rounded first >>> x 6

Notice how the fractional part right of the decimal drops off without rounding, so it is truncated. To round first, use the built-in function round().

3. The Python int() Function

The built-in Python int() function can be called from programs and customized with parameters. A maximum of 2 arguments can be passed.

a. Function syntax
Syntax
int(object)
Pass the function an integer literal (see above).
int(x=0)
When no arguments are passed, the default is 0.
int(x, base=10)
Optionally enter a second parameter for a different base. The default is base 10. Here the object must be a string, bytes or bytesarray class.
b. Function examples

A call to the int() function without assignment prints integer literals (described above) as an integer.

>>> int() # default behavior with no argument 0 >>> int('5') # string conversion 5 >>> int(0b101) # a binary 5 >>> int('101', 2) # 5 in base 2, supplied as string 5

4. Python int Methods

To access methods an assignment must be made to create an int object. Syntax and examples below assume an integer object has been assigned to x.

a. Method syntax

Methods for the integer data type are provided below.

Syntax
x.bit_length()
Returns the number of bits required to represent the provided integer.
x.to_bytes(length, byteorder, *, signed=False)
Returns an array of bytes based on an integer.
x.from_bytes(bytes, byteorder, *, signed=False)
Returns an integer based on an array of bytes.

Because the second two cover more advanced functionality see the official documentation for details.

b. Method examples

Examples of integer data type methods.

>>> x = int(2018) >>> x.bit_length() # find bit length 11 >>> bin(x) '0b11111100010'

5. Find Local Help on Python int

To access local help on the Python int class type help('int') at the Python Interpreter. Output for Python 3.5.3 looks like this.

Help on class int in module builtins: int(object) int(x=0) -> integer int(x, base=10) -> integer Convert a number or string to an integer, or return 0 if no arguments are given. If x is a number, return x.__int__(). For floating point numbers, this truncates towards zero. If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in the given base. The literal can be preceded by '+' or '-' and be surrounded by whitespace. The base defaults to 10. Valid bases are 0 and 2-36. Base 0 means to interpret the base from the string as an integer literal. >>> int('0b100', base=0) 4

Related Python Content


What's Next?

Subscribe to our growing YouTube Channel, a companion to this free online educational website.

  • To see all reference material, click Outline.
  • To see what the reference is all about, click Back.
  • While we work on the next Reference page, Next is disabled.

Outline Back Next

~/ home  / tech  / python  / reference  / python int



 
 
Keywords:
python int
python integer
python int syntax
python integer syntax
python integer examples
python int reference
python integer reference
python int examples
python sting to int
python convert string to int
string to int python
python float to int
python type conversion
python int parameters
python int arguments
python int methods
python int assignment