title | teaching | exercises | questions | objectives | keypoints | |||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Data Types and Type Conversion |
5 |
5 |
|
|
|
- Every value in a program has a specific type.
- Integer (
int
): counting numbers like 3 or -512. - Floating point number (
float
): fractional numbers like 3.14159 or -2.5.- Integers are used to count, floats are used to measure.
- Character string (usually just called "string",
str
): text.- Written in either single quotes or double quotes (as long as they match).
- The quotation marks aren't printed when the string is displayed.
- Use the built-in function
type
to find out what type a value has. - Works on variables as well.
- But remember: the value has the type --- the variable is just a label.
print(type(52))
{: .python}
<class 'int'>
{: .output}
fitness = 'average'
print(type(fitness))
{: .python}
<class 'str'>
{: .output}
- A value's type determines what the program can do to it.
print(5 - 3)
{: .python}
2
{: .output}
print('hello' - 'h')
{: .python}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-2-67f5626a1e07> in <module>()
----> 1 print('hello' - 'h')
TypeError: unsupported operand type(s) for -: 'str' and 'str'
{: .error}
- "Adding" character strings concatenates them.
full_name = 'Ahmed' + ' ' + 'Walsh'
print(full_name)
{: .python}
Ahmed Walsh
{: .output}
- Multiplying a character string by an integer replicates it.
- Since multiplication is just repeated addition.
separator = '=' * 10
print(separator)
{: .python}
==========
{: .output}
- The built-in function
len
counts the number of characters in a string.
print(len(full_name))
{: .python}
11
{: .output}
- But numbers don't have a length (not even zero).
print(len(52))
{: .python}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-3-f769e8e8097d> in <module>()
----> 1 print(len(52))
TypeError: object of type 'int' has no len()
{: .error}
- Cannot add numbers and strings.
print(1 + 'A')
{: .python}
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-fe4f54a023c6> in <module>()
----> 1 print(1 + '2')
TypeError: unsupported operand type(s) for +: 'int' and 'str'
{: .error}
- Not allowed because it's ambiguous: should
1 + '2'
be3
or'12'
? - Use the name of a type as a function to convert a value to that type.
print(1 + int('2'))
print(str(1) + '2')
{: .python}
3
12
{: .output}
- Integers and floating-point numbers can be mixed in arithmetic.
- Python automatically converts integers to floats as needed.
print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
{: .python}
half is 0.5
three squared is 9.0
{: .output}
- If we make one cell in a spreadsheet depend on another, and update the latter, the former updates automatically.
- This does not happen in programming languages.
first = 1
second = 5 * first
first = 2
print('first is', first, 'and second is', second)
{: .python}
first is 2 and second is 5
{: .output}
- The computer reads the value of
first
when doing the multiplication, creates a new value, and assigns it tosecond
. - After that,
second
does not remember where it came from.
What type of value (integer, floating point number, or character string) would you use to represent each of the following?
- Number of days since the start of the year.
- Time elapsed since the start of the year.
- Serial number of a piece of lab equipment.
- A lab specimen's age.
- Current population of a city.
- Average population of a city over time. {: .challenge}
The
//
operator calcultaes the whole-number result of division, while the '%' operator calculates the remainder from division:print('5 // 3:', 5//3) print('5 % 3:', 5%3)
{: .python}
5 // 3: 1 5 % 3: 2
{: .output}
If
num_subjects
is the number of subjects taking part in a study, andnum_per_survey
is the number that can take part in a single survey, write an expression that calculates the number of surveys needed to reach everyone once. {: .challenge}
Where reasonable,
float
will convert a string to a floating point number, andint
will convert a floating point number to an integer:print("string to float:", float("3.4")) print("float to int:", int(3.4))
{: .python}
3.4 3
{: .output}
If the conversion doesn't make sense, however, an error message will occur
print("string to float:", float("Hello world!"))
{: .python}
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-5-df3b790bf0a2> in <module>() ----> 1 print("string to float:", float("Hello world!")) ValueError: could not convert string to float: 'Hello world!'
{: .error}
Given this information, what do you expect this program to do? What does it actually do? Why do you think it does that?
print("fractional string to int:", int("3.4"))
{: .python} {: .challenge}
Which of the following will print 2.0? Note: there may be more than one right answer.
first = 1.0 second = "1" third = "1.1"
{: .python}
first + float(second)
float(second) + float(third)
first + int(third)
first + int(float(third))
int(first) + int(float(third))
2.0 * second
Answer: A and D {: .solution} {: .challenge}
FIXME: introduce complex numbers {: .challenge}