What you will learn
- 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
Reading
Do Now
Open up the console
Type the following code
x_stage1 = 123
y_stage1 = 456
x_stage2 = str(x_stage1)
y_stage2 = str(y_stage1)
print(x_stage2 + y_stage2)
In your Notebook
Answer the following
- What type are the variables
x_stage1andy_stage1? - What type are the variables
x_stage2andy_stage2? - How would you convert a string,
'100'to an integer?
Lab
In your notebook
Predict what the following inputs will result in
Once you have filled in the “prediction” column, check your answers in interactive mode and write the actual result.
| Input | Prediction | Result |
|---|---|---|
float('1') |
||
str(1 + '2') |
||
str('2') |
||
int('abc') |
||
int(float('1.6')) |
||
float(int(1.6)) |
||
str(float(1)) |
In your Console
- Create a program which will take in an input and print out that input divided by 2.
- Alter one line of that program to return only whole numbers.
Bonus
Make your program have two modes: an integer mode and a float mode. Add another input to ask which mode the user wants to use. If the user is in integer mode print out integers, otherwise print out float. Feel free to research Python docs (This is a concept covered in Snap)
Check your understanding
Pick an answer for each question. You can try again until you get it right.
1. After n = "5", what does int(n) + 1 evaluate to?
"51"- 6
- An error
"6"
Casting with int turns the string into a number, so the addition gives the integer 6.
2. Why do you need int() or float() on a value returned by input() before doing math with it?
inputalways returns a float- Math cannot be done in Python
inputalways returns a stringinputreturns nothing
The input function always gives back a string, so you cast it to a number before doing arithmetic.
3. What is the main difference between an integer and a float?
- A float can have a decimal part; an integer is a whole number
- An integer is text; a float is a number
- A float is always bigger than an integer
- There is no difference
Integers are whole numbers, while floats (floating point numbers) can hold fractional values.