Skip to content

Day 2: Bug in 'str to int or float' code example: direct int('10.6') raises ValueError #775

@argony90

Description

@argony90

File: 02_Day_Variables_builtin_functions/02_variables_builtin_functions.md
Section: Lines 230–237

In the section about converting string to int or float, the following code is given:

# str to int or float
num_str = '10.6'
num_float = float(num_str)  # Convert the string to a float first
num_int = int(num_float)    # Then convert the float to an integer
print('num_int', int(num_str))      # 10
print('num_float', float(num_str))  # 10.6
num_int = int(num_float)
print('num_int', int(num_int))      # 10

Problem:

  • The line print('num_int', int(num_str)) will raise a ValueError, because '10.6' (a string with a decimal point) cannot be converted to int directly.
  • int(num_int) in the last line is redundant, since num_int is already an int.
  • The example should demonstrate casting to float first and then to int, using the variables directly in print statements.

Suggestion for corrected code:

num_str = '10.6'
num_float = float(num_str)
num_int = int(num_float)
print('num_float', num_float)  # 10.6
print('num_int', num_int)      # 10

Please fix:

  • Update the code example so it does not suggest using int(num_str) directly with a string containing a decimal value
  • Optionally, add a hint explaining why a direct cast to int will not work for non-integer strings and that an intermediate cast to float is necessary

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions