Int
In Python we use int()
to convert values. The int
keyword is not used to declare values like in other languages. Instead it converts strings and floats.
For floats, int
will always truncate the number (remove the part after the decimal place). So 1.9 will become 1.1. For strings, only valid strings can be converted without an error.
Here we use int()
on some floating-point numbers. We see that the part after the decimal place is removed—the fractional value is discarded.
int()
. Instead it just truncates the value.# Use int to convert floats to integers. # ... The value is always rounded down (truncated). value = 1.5 result = int(value) print(value, "INT =", result) value = 1.9 result = int(value) print(value, "INT =", result) value = -1.9 result = int(value) print(value, "INT =", result)1.5 INT = 1 1.9 INT = 1 -1.9 INT = -1
Parse
string
Now let's use int()
on a string
value. If the string
contains only digits like "123" then we can transform the string
into a number. We test it in an if
-statement.
# Convert a string containing an integer to an int. data = "123" result = int(data) print(data, "INT =", result) # The result is an integer value. if result == 123: print(True)123 INT = 123 True
Int
errorWith int
we must be careful not to try to parse a string
that does not contain an integer value. A ValueError
will occur, and this is disruptive.
# This fails as the string is not in a valid format. data = "cat" result = int(data)Traceback (most recent call last): File "C:\programs\file.py", line 6, in <module> result = int(data) ValueError: invalid literal for int() with base 10: 'cat'
With isdigit()
we can test a string
for an integer value before converting it to an int
with int()
. This prevents the ValueError
on invalid strings.
string
literals. Some of them are valid ints like 123 and 0, but some like "cat" and "bird" are not.int
. Then we parse only the ones that are valid.values = ["123", "cat", "bird", "12.34", "0"] # Loop over strings. for v in values: # See if string is all digits. if v.isdigit(): # Parse string with int. result = int(v) print(v, "INT =", result) else: # String will fail parsing. print(v, "ISDIGIT =", False)123 INT = 123 cat ISDIGIT = False bird ISDIGIT = False 12.34 ISDIGIT = False 0 INT = 0
Int
is an important built-in function in Python. It is not used to specify an integer like 5. But it can convert a string
like "5" to 5, or a float
like 5.3 to an integer.