Asabeneh / 30-Days-Of-Python

30 days of Python programming challenge is a step-by-step guide to learn the Python programming language in 30 days. This challenge may take more than100 days, follow your own pace. These videos may help too: https://www.youtube.com/channel/UC7PNRuno1rzYPb1xLa4yktw
40.59k stars 7.74k forks source link

02_variables_builtin_functions.md example code #547

Open BVenetta opened 1 month ago

BVenetta commented 1 month ago

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 commented 1 month ago

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.