Turning a str Into a float
The Python programming language uses data types to distinguish between different types of information.
Dependencies
Students need to have these skills before learning this skill:
Goal
When you teach this skill, your goal is to make it so that students can write code that looks like this:
number_1 = input("Enter a number: ")
number_1 = float(number_1)
number_2 = input("Enter a second number: ")
number_2 = float(number_2)
print("Total:")
print(number_1 + number_2)
Activities
Here are some activities that you can do in order to teach this skill.
Why does this code break?
-
Write this code on the board:
number = input("Enter a number: ")
print(number + 1) -
Ask students what they think that code will do.
-
Run the code.
-
Ask students why the code broke. After calling on a few students, reveal the correct answer.
-
Change the code to fix the problem:
number = input("Enter a number: ")
number = float(number)
print(number + 1) -
Explain how your changes fix the problem.
-
Have students write a similar program on their computers.