Students will be able to...
- Define and identify: type, string, casting, floating point number (float), integer
- Describe different representations of data in Python
- Convert from one data type to another data type
- 2.01 Slide Deck
- Do Now
- Lab - Casting (docx) (pdf)
- Associated Readings 2.1
- Read through the do now, lesson, and lab so that you are familiar with the requirements and can assist students
- Video Resources
Duration | Description |
---|---|
5 Minutes | Do Now |
10 Minutes | Lesson |
35 Minutes | Lab |
5 Minutes | Debrief |
- Project the Do Now on the board, circulate around the class to check that students are working and understand the instructions.
- Ask students to define type. Talk about types as a way to represent data (give examples of
strings
,int
, andfloat
). - Ask students what they thought typing the command
str(123)
does.
- Define this process of changing data types as casting.
- Define the
int
function if the students were unable to guess it from the Do Now. - Demonstrate casting
string
toint
by typing in the following:
n = int(input())
9
type(n)
Output from Python:
<class 'int'>
- Because Python 3 is strongly typed, concatenating strings and numbers requires casting. Demonstrate by typing the following:
n = int(input())
9
print ("You entered " + n)
Output from Python:
TypeError: Can't convert 'int' object to str implicitly
- Cast the integer to a string. Demonstrate by typing the following:
n = int(input())
9
print ("You entered " + str(n))
Output from Python:
You entered 9
- Take a few minutes to have students write down how they would produce the following output:
Give me a number you want to multiply by 2: 4
8
- Explain to students that in Python
- when asking for input from the user, the input is automatically stored as a string
- if the input will be used for calculations or numeric comparisons, it will be necessary to cast it to another data type.
- Go over the method of swapping two variables using Python syntax covered so far, with a third temporary variable.
- Python includes a way to swap two variables directly. The syntax for this will be covered in a later unit.
- Call on 2-3 students to write their answers on the board.
- Discuss what would happen if the user types in 1.5 instead of 4.
- If input is a float, can cast with
float(num)
type
: ask students what they thinktype('a')
would output.- Why might you want to use
type
?
- Practice predicting what casting will do to inputs.
- Create a halving program, and a variant of the same program that converts any fractional output values to whole numbers.
- Check student progress and completion of the lab, wrap up by taking any final questions.
If students are moving quickly, it is possible to introduce the concepts of Booleans here. Discuss how students would represent binary (0's and 1's). In practice these translate to True and False. Convert numbers to Boolean, and Booleans to numbers.