30-Days-Of-Python
30-Days-Of-Python copied to clipboard
02_variables_builtin_functions.md example code
Error in example for Casting in section Checking Data types and Casting for the following code;
num_int = 10
print('num_int',num_int) # 10
num_float = float(num_int)
print('num_float:', num_float) # 10.0
# float to int
gravity = 9.81
print(int(gravity)) # 9
# int to str
num_int = 10
print(num_int) # 10
num_str = str(num_int)
print(num_str) # '10'
# str to int or float
num_str = '10.6'
print('num_int', int(num_str)) # 10
print('num_float', float(num_str)) # 10.6
# str to list
first_name = 'Asabeneh'
print(first_name) # 'Asabeneh'
first_name_to_list = list(first_name)
print(first_name_to_list) # ['A', 's', 'a', 'b', 'e', 'n', 'e', 'h']
Error:
print('num_int', int(num_str)) # 10
^^^^^^^^^^^^
ValueError: invalid literal for int() with base 10: '10.6'```
Your code is attempting to convert the string '10.6' directly to an integer, which is not allowed because '10.6' is in a floating-point number format and cannot be directly converted to an integer. To fix this, you can first convert the string to a float, and then convert the float to an integer.
Here is the corrected code:
num_str = '10.6'
# First convert to a float, then to an integer
num_float = float(num_str)
num_int = int(num_float)
print('num_int', num_int) # Output will be 10
print('num_float', num_float) # Output will be 10.6
Explanation:
- Use
float(num_str)to convert the string to a float10.6. - Then, use
int(num_float)to convert the float to an integer10(which automatically truncates the decimal part).
This approach avoids the ValueError you encountered.
I hope this helps you. If you need further assistance, feel free to reach out via WeChat at pythonbrief.