int() function in Python
Python int() function returns an integer from a given object or converts a number in a given base to decimal.
Python int() Syntax :
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Python int() Parameter :
- string : consists of 1’s and 0’s
- base : (integer value) base of the number.
Python int() Returns :
Returns an integer value, which is equivalent of binary string in the given base.
Python int() Exception and Errors :
TypeError : Returns TypeError when any data type other than string or integer is passed in its equivalent position.
Python int() method example
Example 1: Working with int() function in Python
int('187') + 13 = 200 int('100') with base 2 = 4 int('100') with base 4 = 16 int('100') with base 8 = 64 int('100') with base 16 = 256
Example 2: Convert binary string to Python int base
Decimal equivalent of binary 111 is 7 Decimal equivalent of octal 101 is 65
Example 3: Program to demonstrate the TypeError
TypeError: int() can't convert non-string with explicit base
Example 4: Python int() Exception
invalid literal for int() with base 10: ‘Geeks’
It is used in all the standard conversions. For example conversion of binary to decimal, octal to decimal, hexadecimal to decimal.