Hit enter after type your search item

Python int() function

The int function in Python is used to convert a given value into an integer. For example:

Num = int(10.5)

Str_num = int(“10.5”)

The function returns an integer object. The object is constructed from the given string or number. If no arguments are given then it returns 0.

Syntax of int() function

The general syntax for using the int() function is:

class int([x])

OR

class int(x, base=10)

Where,

The x can be a number or string, bytes or bytearray instance that represents integer literal. The default value for the base argument is 10.

The base argument is explained further in the section below with examples.

An example of int() using a float number

The following example shows using the int() function where x argument is float number. Have a look how it outputs the given number:


The output:

25

20

30

The example of using a string

This example uses are a string representing the integer literal. See how int() function converts string to int:


The result:

11

15

21

Using base argument in the int() function

The default value for the base argument is 10. That means using normal math i.e. 0123456789.

You may provide from 2 to 36 value. Similarly, base 36 value uses symbols from:

0123456789abcdefghijklmnopqrstuvwxyz

The examples below show using different base values in the int() function for string to int conversion:

Using base value 36 example:


The result:

10

35

1

36

Example of using base 16

See the output for various values given with base 16:


The output:

1

10

15

16

Using base value 2 – binary

In this example, the base value 2 is used that represents binary. It has only two symbols i.e. 0 and 1. In the binary system, 1000 is equal to 8 in decimal. Similarly, 10000 is equal to 16.

The code below shows using base value 2:


The output:

8

1

4

16

The example of using base 8 – Octal

The octal system has eight symbols for representing all quantities. The symbols are:

0,1,2,3,4,5,6,7

The example below shows converting the string to octal:


The output:

520

320

7

3

This div height required for enabling the sticky sidebar