## Types and type()¶

Values in Python have different types. You can find the type of a value using type()

In [23]:
type(42)

Out[23]:
builtins.int

In Python, the integer type is called int

In [2]:
type(3.14)

Out[2]:
builtins.float
In [24]:
type("Hello")

Out[24]:
builtins.str

In Python, the string type is called str

Note that an expression like 40 + 2 is evaluated to a value with a type

In [12]:
type(40 + 2)

Out[12]:
builtins.int

Something like this would also work:

In [13]:
n = 5
type(n + 2)

Out[13]:
builtins.int
In [25]:
type(n)

Out[25]:
builtins.int

## Floats¶

If we perform division, we will get a type that's different from the type of the values in the expression:

In [7]:
type(5/2)

Out[7]:
builtins.float
In [8]:
type(4/2)

Out[8]:
builtins.float

Why is type(4/2) still float, even though 4 is divisible by 2? For consistency. Division always produces a float.

Multiplying a string by an integer produces a string (remember that "ha" * 2 is "haha". Multiplying an integer by a float produces a float (think about this like this: if we multiply a fraction by an integer, we can't be sure we'll get an integer. For consistency, we'll always produce a float)

In [21]:
type(2 * 3.14)

Out[21]:
builtins.float

We can go a little crazy:

In [10]:
type(type(42))

Out[10]:
builtins.type

In [11]:
type(print)

Out[11]:
builtins.builtin_function_or_method

Here are the types of values that we've seen so far: Integer (int): a whole number (positive or negative). In Python 3 (which we are using), ints can be as large as you like, as long as there is enough space in memory to store them.

Floating-point number (float): a fractional number (like 3.14, 5.0, 4.0, or 10000.5). In the computer, floats are stored in scientific notation, with up to about 16 (decimal) digits in the mantissa and about 3 digits in the exponent (the exponent can go from about -300 to 300).

(Reminder about scientific notation: in scientific notation, numbers are stored in the format $m\times b^n$. For example, Avogadro's number is $6.02\times 10^23 mol^{-1}$. $m$ is called the mantissa, and $n$ is called the exponent, and $b$ is called the base.)

This means that we can't have numbers that are too large, or too close to 0, and can't store number with more than 16 digits of precision.

In [19]:
1.0 * 10**300

Out[19]:
1e+300
In [26]:
1.0 * 10**350

---------------------------------------------------------------------------
OverflowError                             Traceback (most recent call last)
<ipython-input-26-48bdbd7d799e> in <module>()
----> 1 1.0 * 10**350

OverflowError: int too large to convert to float

## Strings¶

Strings are another type that we saw. Expressions like "Hi", "H2O", and 'Hi' + "there" are all of type str. You can enclose text in single or double quotes, as you as you are consistent. The string must be written on a single line:

In [27]:
'abc'

Out[27]:
'abc'
In [28]:
"abc"

Out[28]:
'abc'
In [29]:
"ab
c"

  File "<ipython-input-29-b218b3cee1e4>", line 1
"ab
^
SyntaxError: EOL while scanning string literal


You can store strings that contain multiple lines:

In [77]:
'''a
bcd
ef'''

Out[77]:
'a\nbcd\nef'

(Recall that we can have values written in the text of Python programs that Python will simply ignore. We sometimes have multi-line strings in programs that basically act as comments.)

\n is a special character. It means "switch to a new line."

In [31]:
print("ab\ncd")

ab
cd


Suppose we want quotes inside quotes:

In [32]:
"Getting into medical school is "easy""

  File "<ipython-input-32-607959b05a1f>", line 1
"Getting into medical school is "easy""
^
SyntaxError: invalid syntax


That didn't work! The reason is that Python reads from left to right. "Getting into medical school is " makes sense, but the easy that follows makes no sense to Python.

There are two solutions: one is to mix single quotes and double quotes:

In [34]:
'Getting into medical school is "easy"'

Out[34]:
'Getting into medical school is "easy"'
In [35]:
"Getting into medical school is easy'"

Out[35]:
"Getting into medical school is easy'"

Another is to use \" inside double quotes to let Python know that you don't mean to terminate the string

In [36]:
"Getting into medical school is \"easy\""

Out[36]:
'Getting into medical school is "easy"'

(Note that Python itself uses the mixed quotes notation)

(But how do you put forward slashes in quotes? Use "\\" for a single forward slash.)

## Converting values to different types¶

We already saw an example of converting from one type to another when we used n = float("Give me a number"). You can convert a string to a float:

In [41]:
float("3.14")

Out[41]:
3.14

(You can tell the value is a float because of the lack of quotes when the value is displayed in the shell. But note that if we use print(), both string and floats are printed without quotes)

In [43]:
print(float("3.14"))
print("3.14")

3.14
3.14


Recall that converting from a string to a float is useful if we want to perform arithmetic operations on a value that is stored as text (for example, because we got the value as input from a user)

In [46]:
print("42" * 2)
print(float("42") * 2)

4242
84.0


If we try to convert something that's not a number to a float, we'll get an error

In [48]:
float("forty-two")

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-48-f991ea6ec533> in <module>()
----> 1 float("forty-two")

ValueError: could not convert string to float: 'forty-two'

Converting floats to string makes sense if, for example, we want to use "string addition":

In [50]:
"abc" + 123

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-50-1e18b1af5699> in <module>()
----> 1 "abc" + 123

TypeError: Can't convert 'int' object to str implicitly

But:

In [51]:
"abc" + str(123)

Out[51]:
'abc123'

Floats and strings can be converted to integers:

In [52]:
int(3.14)

Out[52]:
3
In [53]:
int(3.75)

Out[53]:
3

(Integers are truncated rather than rounded)

In [54]:
int("42")

Out[54]:
42
In [55]:
int("42.3")

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-55-6076aa6f9770> in <module>()
----> 1 int("42.3")

ValueError: invalid literal for int() with base 10: '42.3'

Doesn't work: the string must contain an integer to be converted. But we have the tools to do this:

In [57]:
int(float("42.3"))

Out[57]:
42

## Converting strings to lists and using strings as iterables¶

You can convert strings to lists:

In [60]:
list("abc")

Out[60]:
['a', 'b', 'c']

We got a list that consists of the individual characters of the string. This suggests a way to find out the length of the string, and get the individual character of a string (by going list("abc")[1]). But in fact, there is an easier way: you can just treat the string the way we treated lists:

In [61]:
s = "abc"
s[1]

Out[61]:
'b'

In fact, you can directly go

In [62]:
"abc"[2]

Out[62]:
'c'

You can also find the length of a string (i.e., the number of characters the string has) like so:

In [64]:
len("hello")

Out[64]:
5

## Booleans¶

Another type that we already so was Booleans (bool type in Python). Those values can be either True or False. We already saw this kind of thing:

In [65]:
2 == 3

Out[65]:
False

In fact, 2 == 3 is an expression in the same way that 2 + 3 is an expression, and both of those are evaluated to a value. In the same way that we can say sum23 = 2 + 3 we can go

In [66]:
are_equal_2_3 = (2 == 3)
print(are_equal_2_3)

False

In [72]:
x = are_equal_2_3
print(x == are_equal_2_3)

True


Generally, we would see Boolean values used in conditionals. A Boolean value is what goes after the if.

In [73]:
if x == are_equal_2_3:
print("The world makes sense")
else:
print("The world doesn't make sense")

The world makes sense

In [75]:
if are_equal_2_3:
print("The world doesn't make sense")
else:
print("The world makes sense")

The world makes sense


(We can check that the values are indeed of type bool:

In [70]:
type(2 != 3)

Out[70]:
builtins.bool
In [71]:
type(False)

Out[71]:
builtins.bool

)