ValueError is encountered when we pass an inappropriate argument type. Here, we are talking about the ValueError caused by passing an incorrect argument to the
int() function. When we pass a string representation of a float or any string representation other than that of int, it gives a ValueError.
Example 1 : ValueError with base 10.
ValueError: invalid literal for int() with base 10: '23.5'
One can think that while executing the above code, the decimal part ‘.5’ should be truncated and the code should give output as 23 only. But the point to be noted is that the int( ) function uses the decimal number system as its base for conversion ie. base = 10 is the default value for conversion. And in the decimal number system, we have numbers from 0 to 9 excluding the decimal (.) and other characters(alphabets and special chars). Therefore,
int() with base = 10 can only convert a string representation of int and not floats or chars.
We can first convert the string representation of float into float using
float() function and then convert it into an integer using
Example 2 : Passing alphabets in
invalid literal for int() with base 10: 'abc'
The chars a, b, c, d, e, and f are present in the base =16 system and therefore only these chars along with digits 0 to 9 can be converted from their string representation to integer in hexadecimal form. We have to pass an parameter
base with value 16.
- How to compute natural, base 10, and base 2 logarithm for all elements in a given array using NumPy?
- Python program to check if the given string is IPv4 or IPv6 or Invalid
- How to handle invalid arguments with argparse in Python?
- Python program to convert any base to decimal by using int() method
- String to Int and Int to String in Python
- Selenium Base Mini Project Using Python
- Python | Pandas TimedeltaIndex.base
- PyQt5 QSpinBox - Access display integer base
- PyQt5 QSpinBox - Setting display integer base
- PyQt5 QSpinBox - Setting base size
- PyQt5 QSpinBox - Getting base size
- PyQt5 QCalendarWidget - Accessing Base Size value
- PyQt5 QCalendarWidget - Assigning Base Size value
- numpy.dtype.base() function - Python
- NseTools - Getting Base Price of Comapny Stock
- Abstract Base Class (abc) in Python
- Python | int() function
- Assigning multiple characters in an int in C language
- Python bit functions on int (bit_length, to_bytes and from_bytes)
- Scala short ==(x: Int): Boolean
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.