Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

02_variables_builtin_functions.md example code #547

Open
BVenetta opened this issue Jul 4, 2024 · 1 comment
Open

02_variables_builtin_functions.md example code #547

BVenetta opened this issue Jul 4, 2024 · 1 comment

Comments

@BVenetta
Copy link

BVenetta commented Jul 4, 2024

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'```
@XksA-me
Copy link

XksA-me commented Jul 5, 2024

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:

  1. Use float(num_str) to convert the string to a float 10.6.
  2. Then, use int(num_float) to convert the float to an integer 10 (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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants