GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.geeksforgeeks.org — Python int() Function - GeeksforGeeks Python int() FunctionLast Updated : 26 Sep, 2025 The Python int() function converts a given object to an integer or converts a decimal (floating-point) number to its integer part by truncating the fractional part. Example: In this example, we passed a string as an argument to the int() function and printed it.
Output:
Python int() Function SyntaxThe syntax of the int() function in Python is as follows:
Python int() Function ExamplesLet us see a few examples of int() in Python. Python int() with different DataTypesIn this example, we passed a string, a float, and an integer value as a parameter to the int() function in Python to see how the input is affected by applying the int() function.
Output :
Convert base using int() in PythonIn this example, we used the int() function to convert the base of a number from Binary, Octal, and Hexadecimal to a Decimal integer.
Output : int() on 0o12 = 10 Exception of int() in PythonTypeError: raises TypeError when any object that does not have __int__() or __index__() Python magic methods implemented. ValueError: raises ValueError when any object cannot be converted to an integer. TypeError: int() can't convert non-string with explicit baseIn this example, we are trying to convert a binary number to a decimal number using the Python int() function. But this code will raise an error as the binary number passed is not in a single quote.
Output:
ValueError: invalid literal for int() with base 10: 'geeks'This example will generate a value error as we are passing a Python String to the int() function.
Output:
Python int() Function for Custom ObjectsThe int() in Python can be used on custom objects. Let us see a few examples of the same. int() with __int__() functionIn this example, we created a class called Number and defined a __int__() method that returns the integer value. Then we created an object called data of the Number class. When we pass this object to the int() function, Python internally invokes the __int__() method, and the returned value is used as the integer representation.
Output:
int() with __index__() functionIn this example, we created a class called 'Number' and defined a value and a function that returns the value. Then we created an object called 'data' of the Number class which invokes the __index__() method. The data object stores the value that is returned by that method and then using the int() function we printed the value.
Output:
Comment Explore |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |