hello,
I am trying to write a Python script that converts a list of numbers containing integers and floating point numbers into a list of integers. I used the Geany editor for the script and the Idle shell to test it:
numbers = input(“enter a list of numbers separated by commas: “) list = numbers.split(”,”) list_integers = [] for numbers in list: integers = int(numbers) list_integers.append(integers) print(list_integers)
If I enter the numbers [1, 6.3]I get this error :
Traceback (most recent call last): File “<pyshell#91>”, line 2, in integers = int(numbers) ValueError: invalid literal for int() with base 10: ’ 6.3’
If I replace 6.3 with 6, everything works correctly. Why does the int() function not accept a floating point number in this specific case?
PS: I am just starting to learn the Python language.
If you pass in a floating point number, it will truncate the number and return an integer value.
If you pass in a string[1]that represents an integer, it will convert the string to a number and return that integer.
It does not take a string that represents a floating point number and do both steps of converting from the string and truncation. If you want to do that, you might instead do int(float(x)).
Using link #2, I think I’ve found the explanation for my mistake:
1- I thought the int() argument was a number: 6.3. In reality, it was a string: “6.3”.
2- In the documentation Built-in Functions — Python 3.13.7 documentation I found this line: If the argument is not a number or if base is given, then it must be a string, bytes, or bytearray instance representing an integer in radix base.
So int(“6.3”) cannot be interpreted because the decimal point has no associated value and cannot be represented by a number. This must be the reason for “It does not accept a string that represents a floating point number.”
That is how I interpret my error.