Python int()
Python int() builtin function is used to create an integer object from a number of string, and an optional base value.
In this tutorial, we will learn about the syntax of Python int() function, and learn how to use this function with the help of examples.
Syntax
The syntax of int() function with a number or string as parameter is
int([x])
where
Parameter | Required/Optional | Description |
---|---|---|
x | Optional | A number or string. |
The syntax of int() function is
int(x, base=10)
where
Parameter | Required/Optional | Description |
---|---|---|
x | Mandatory | A number or string. |
base | Optional | The base value of the number x . |
Returns
The function returns an int object.
Examples
1. Convert float to integer
In this example, we will give a number as argument to int() function, and print the int() function’s return value.
Python Program
x = 10.2
result = int(x)
print(result)
Output
10
2. int() – No Argument
If no argument is passed to int() function, then it returns 0.
Python Program
result = int()
print(result)
Output
0
3. int(x) – x is String
If a string is given as argument to int() function, then int() tries to convert the given string into an integer.
Python Program
x = '25'
result = int(x)
print(result)
Output
25
If the string has any spaces on its edges, they would be trimmed.
Python Program
x = ' 25 '
result = int(x)
print(result)
Output
25
4. int(x, base)
In this example, we will give a string value '25'
for x parameter and a value of 7
for base parameter to int() function. int() function should return a resulting value to the base 10.
Python Program
x = '25'
base = 7
result = int(x, base)
print(result)
Output
19
Explanation
25 to the base 7 = 2*7 + 5 to the base 10
= 19 to the base 10
5. int(number, base) – TypeError
We could explicitly specify the base, only if the parameter x is of type string. If we provide a number for parameter x and specify a base, then int() function throws TypeError.
Python Program
x = 26.5
base = 7
result = int(x, base)
print(result)
Output
Traceback (most recent call last):
File "d:/workspace/python/example.py", line 3, in <module>
result = int(x, base)
TypeError: int() can't convert non-string with explicit base
Conclusion
In this Python Tutorial, we have learnt the syntax of Python int() builtin function, and also learned how to use this function, with the help of Python example programs.