Questions:

  • What kinds of data do programs store?
  • How can I convert one type to another?

Objectives:

  • Explain key differences between integers and floating point numbers.
  • Explain key differences between numbers and character strings.
  • Use built-in functions to convert between integers, floating point numbers, and strings.

Keypoints:

  • Every value has a type.
  • Use the built-in function type to find the type of a value.
  • Types control what operations can be done on values.
  • Strings can be added and multiplied.
  • Use an index to get a single character from a string.
  • Use a slice to get a substring.
  • Use the built-in function len to find the length of a string.
  • Convert numbers to strings or vice versa when operating on them.
  • You can mix integers and floats freely in operations.
  • Variables only change value when something is assigned to them.

Every value has a type.

  • Every value in a program has a specific type.
  • Integer (int): represents positive or negative whole numbers like 3 or -512.
  • Floating point number (float): represents real numbers like 3.14159 or -2.5.
  • Character string (usually called "string", str): text.
    • Written in either single quotes or double quotes (as long as they match).
    • The quote marks aren't printed when the string is displayed.

Use the built-in function type to find the type of a value.

  • 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))
<class 'int'>
fitness = 'average'
print(type(fitness))
<class 'str'>

Types control what operations (or methods) can be performed on a given value.

  • A value's type determines what the program can do to it. For example, you can subtract two integers but not two strings.
print(5 - 3)
2
print('hello' - 'h')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/5q/mny3pg2n7h5g21h3v32rfj9wpykqrf/T/ipykernel_11287/13340790.py in <module>
----> 1 print('hello' - 'h')

TypeError: unsupported operand type(s) for -: 'str' and 'str'

You can use the "+" and "*" operators on strings.

  • "Adding" character strings concatenates them.
full_name = 'Ahmed' + ' ' + 'Walsh'
print(full_name)
Ahmed Walsh
  • Multiplying a character string by an integer N creates a new string that consists of that character string repeated N times.
separator = '=' * 10
print(separator)
==========

You can index to get a single character from a string.

  • The characters (individual letters, numbers, and so on) in a string are ordered. For example, the string 'AB' is not the same as 'BA'. Because of this ordering, we can treat the string as a list of characters.
  • Each position in the string (first, second, etc.) is given a number. This number is called an index or sometimes a subscript.
  • Indices are numbered from 0.
  • Use the position's index in square brackets to get the character at that position.
atom_name = 'helium'
print(atom_name[0])
h

Use a slice to get a substring.

  • A slice is a part of a string
  • We take a slice by using [start:stop], where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want.
  • Mathematically, you might say that a slice selects [start:stop).
  • The difference between stop and start is the slice's length.
  • Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.
  • You can slice any list-like thing and we will come back to slicing several times in this course
atom_name = 'sodium'
print(atom_name[4:6])
um

Use the built-in function len to find the length of a string.

print(len('helium'))
6
  • Nested functions are evaluated from the inside out, just like in mathematics.
  • len is a built-in function because it is always available - you do not need to import a particular library to access it
  • Numbers do not have a length
print(len(52))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/5q/mny3pg2n7h5g21h3v32rfj9wpykqrf/T/ipykernel_11287/2246900780.py in <module>
----> 1 print(len(52))

TypeError: object of type 'int' has no len()

Convert numbers to strings or vice versa when operating on them.

  • You cannot add numbers and strings.
print(1 + '2')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/5q/mny3pg2n7h5g21h3v32rfj9wpykqrf/T/ipykernel_11287/3905401405.py in <module>
----> 1 print(1 + '2')

TypeError: unsupported operand type(s) for +: 'int' and 'str'
  • This is not allowed because it's ambiguous: should 1 + '2' be 3 or '12'?
  • Some types can be converted to other types by using the type name as a function.
print(1 + int('2'))
print(str(1) + '2')
3
12

You can mix integers and floats freely in operations.

  • Integers and floating-point numbers can be mixed in arithmetic.
  • Python 3 automatically converts integers to floats as needed.
print('half is', 1 / 2.0)
print('three squared is', 3.0 ** 2)
half is 0.5
three squared is 9.0

Variables only change value when something is assigned to them.

  • 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)
first is 2 and second is 5
  • The computer reads the value of first when doing the multiplication, creates a new value, and assigns it to second.
  • The value of second is not updated when we re-assign the value of first.

Tip: By now we have seen plenty of Error messages. Don’t be afraid of Error messages - they won’t break the computer! In the next lesson we will learn how to use these messages to fix our code more efficiently.