int function in python

Python library provides an int function which is used

  1. To convert a python string to an integer.
  2. To convert a number of a given base to a decimal. Here, decimal does not mean floating numbers but a number having base 10.

int function arguments
int function accepts 2 arguments.

  • First is the number, it may be supplied as an integer or a string.
  • Second is the base(or number system) of the first argument.

Syntax
Based on the above explanation, syntax of int function is

int(number, base)

where number may be an integer or a string which can be converted to an integer.
Both arguments are optional. If not provided, first argument(number) is assumed to be 0 and second argument(or base) it is assumed to be 10.
Return Type
int returns an integer representation(or base 10 equivalent) of the first argument.
When called with a single argument, int will return the same value converted to an integer and when called without any arguments, int will return 0.
Examples of usage of int are given below.

# with 2 arguments
print(int(20), 10)    # prints 20
print(int('20', 10))  # prints 20

# with a single argument
print(int(20))  # prints 20 
print(int('20') # prints 20

# without argument
print(int())  # prints 0

Examples
int function can be used to convert a string to an integer, convert a binary value to decimal or convert a hexadecimal value to a decimal number.
Below are the usage examples of int.

# string
num_str = '30'
print('---- Converting string to integer ----')
# print its type
print(type(num_str))
# convert to integer
num = int(num_str)
# print its type
print(type(num_str))

print('---- Converting binary to decimal ----')
print(int('10',2))
print('---- Converting hex to decimal ----')
print(int('A',2))
print('---- Converting octal to decimal ----')
print(int('1001',8))

Below is the output

—- Converting string to integer —-
<class ‘str’>
<class ‘int’>
—- Converting binary to decimal —-
2
—- Converting hex to decimal —-
10
—- Converting octal to decimal —-
513

Look at the types of values, int converted a string to an integer.

Errors thrown by int
int function will throw following errors.
TypeError
If base(second argument) is given, then the first argument must be a string, bytes or a bytearray else a TypeError will be raised.
Thus, below code will raise an error.

num = 10
print(int(num,10)) # Error

TypeError: int() can’t convert non-string with explicit base

ValueError
If the base and the number do not match, then a ValueError will be raised by int. Below code will result in an error.

int('A', 2)

ValueError: invalid literal for int() with base 2: ‘A’

This is because ‘A’ is not a binary value.
Do not forget to hit the clap.

0
Liked the article ? Spread the word...

Leave a Reply