C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Python int() FunctionPython int() function is used to get the integer value. It returns an expression converted into an integer number. If the argument is a floating point, the conversion truncates the number. If the argument is outside the integer range, It converts the number into long type. If the number is not a number or if a base is given, the number must be a string. Signature
int(x, base=10) Parameters
x : A number which is to be converted into integer type. base: It is an Optional argument if used number must be a string. Return
It returns an integer value. Let's see some examples of int() function to understand it's functionality. Python int() Function Example 1It is a simple python example which converts float and string values into an integer type. The float value is truncated by the function and returned an integer instead.
# Python int() function example
# Calling function
val = int(10) # integer value
val2 = int(10.52) # float value
val3 = int('10') # string value
# Displaying result
print("integer values :",val, val2, val3)
Output: integer values : 10 10 10 Python int() Function Example 2To verify the type of returned value, we can use type function. The type function returns the type of value. See an example below.
# Python int() function example
# Declaring variables
val1 = 10 # integer
val2 = 10.52 # float
val3 = '10' # string
# Checking values's type
print(type(val1), type(val2), type(val3))
# Calling int() function
val4 = int(val1)
val5 = int(val2)
val6 = int(val3)
# Displaying result
print("values after conversion ",val4, val5, val6)
print("and types are: \n ", type(val4), type(val5), type(val6))
Output: <class 'int'> <class 'float'> <class 'str'> values after conversion 10 10 10 and types are: <class 'int'> <class 'int'> <class 'int'> Python int() Function Example 3
# Python int() function example
# Declaring variables
val1 = 0b010 # binary
val2 = 0xAF # hexadecimal
val3 = 0o10 # octal
# Calling int() function
val4 = int(val1)
val5 = int(val2)
val6 = int(val3)
# Displaying result
print("Values after conversion:",val4, val5, val6)
print("and types are: \n ", type(val4), type(val5), type(val6))
Output: Values after conversion: 2 175 8 and types are: <class 'int'> <class 'int'> <class 'int'>
Next TopicPython Functions
|