Types in python

Table of Contents

Boolean

Boolean values are represented by True and False. They are often produced by comparison operations.

print(3 > 2)
print(10/5 == 1)
True
False

Note: Above I am using print to see the results of the comparison, but if you're in IPython, you don't need to do this.

Integers

x = 1
print(x + 3)
4

Floats

x = 1.0
print(x + 3.0)
4.0

If you add an integer to a float, the result will be a float.

x = 1.0
print(x + 3)
4.0

Strings

These are characters and words. They must be surrounded by either single or double quotes.

name = 'john'

Strings have some convenient methods associated with them. For example:

print(name.upper())
print(name.capitalize())
JOHN
John

Note: If you're in IPython, you can find out what methods are available for an object (like the string name above) by typing the object and a period and then hitting tab. So, in this case, name.<TAB> will show you all the available methods for a str.

Lists

A list is a sequence of values.

primes = [2, 3, 5]

Each value can be accessed individually.

print(primes[0])
print(primes[2])
2
5

The index (the value inside the brackets) is 0-based.

Lists can also be iterated over one-by-one.

for prime in primes:
    print(prime)
2
3
5

Dictionaries

Dictionaries store key-value pairs.

prices = {'car' : 40000, 'pop' : 1}
print(prices['pop'])
1

Released under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Created with Emacs 24.4.1 (Org mode 8.3beta)

Validate