Variables and Basic Data Types

In this section we discuss variables and the basic built-in data types. At the end of the section we review some useful methods associated with the data types.

Variables can be assigned to objects in Python. We do not need to declare or define them in advance.

Variables

>>> x = 10
>>> y = 15
>>> z = 20
>>> x * y / z
7.5

There is a nice style guide for Python Code, PEP 8, that includes recommended naming conventions. For variables PEP 8 recommends using lowercase letters with any words separated by underscores.

>>> m = 2
>>> x = 3
>>> b = -1
>>> y = m*x + b
>>> y
5
>>> rate_in_mph = 60
>>> time_in_hours = 5
>>> distance_in_miles = rate_in_mph * time_in_hours
>>> distance_in_miles
300

These examples illustrate the typical use of white space in Python expressions.

Basic Data Types

Python has a number of built-in data types. We separate the basic ones into the groups and introduce them with examples.

Numeric Types

There are three basic numeric types int (integers), float (floating point numbers), and complex (complex numbers). We introduce the type function, type(argument), here. It returns the type of the argument. We will introduce more built-in functions soon and user-defined functions in later sections.

Integers:

>>> x = 7
>>> y = 8
>>> z = 9
>>> (x ** y) ** z
7031676478883553279994550741476882515263791803223057265323201

Floating point numbers:

>>> pi = 3.14
>>> r = 6
>>> A = pi * r ** 2
>>> A
113.04

Complex numbers:

>>> v = 1 + 2j
>>> w = 1 - 2j
>>> x = j
>>> x = 1j
>>> v * w
(5+0j)
>>> w ** 10
(237+3116j)
>>> x ** 101
(4.408109496293883e-15+1j)
>>> x ** 11
(-0-1j)

Continuing with the variables assigned above, the type function would output the following:

>>> type(x)
<class 'int'>
>>> type(pi)
<class 'float'>
>>> type(w * v)
<class 'complex'>

Sequence Types

Lists are commonly used to store heterogenous objects. The objects are separated by commas and enclosed with square brackets.

>>> list1 = [] # empty list
>>> list2 = ['a', 'b', 1, 2]
>>> list3 = [1j, -1j]
>>> type(list3)
<class 'list'>

Note that a hashtag (#) is used in Python to indicate a comment.

The tuple is used for a sequence of homogeneous objects. The objects are separated by commas and enclosed with parentheses.

>>> w = (1, 2, 3)
>>> type(w)
<class 'tuple'>

A range is a sequence of integers. The range type is commonly used with loops. We will introduce loops later. Here will use the list(), set(), and tuple() constructors to illustrate how range works. Range is used as follows: range(start, stop, step) where start, stop, and step are integers. Both start and step are optional. The default for start is 0 and the default for step is 1. Note that range will begin with start and increment by step. It will end on the iteration just before it reaches stop.

>>> range(3)
range(0, 3)
>>> type(range(3))
<class 'range'>
>>> list(range(3))
[0, 1, 2]
>>> list(range(0, 10, 2))
[0, 2, 4, 6, 8]
>>> tuple(range(5, -5, -1))
(5, 4, 3, 2, 1, 0, -1, -2, -3, -4)

Text Type

Strings are written with single, double or triple quotes. Triple quoted strings can span multiple lines.

>>> str1 = 'abc'
>>> str2 = "one, two, three"
>>> str3 = """Roses are red.
... Violets are blue."""
>>> str3
'Roses are red.\nViolets are blue.'
>>> type(str1)
<class 'str'>

Boolean Type

There are two boolean types, True and False. Both are capitalized.

>>> type(true)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'true' is not defined
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>

Set Type

Sets are unordered collections with no repeated elements. They can be thought of as sets in the mathematical sense, that is, as unordered collections with no repeated elements. They can be constructed by surrounding a list with curly braces or from a sequence with the set() function. The set operations of union, intersection, and set difference are supported. Each in two ways. Here are examples:

>>> A = {'a','b', 'y', 'z'}
>>> B = {'b', 'c', 'y'}
>>> A.union(B)
{'b', 'a', 'y', 'c', 'z'}
>>> A | B
{'b', 'a', 'y', 'c', 'z'}
>>> A.intersection(B)
{'b', 'y'}
>>> A & B
{'b', 'y'}
>>> B.difference(A)
{'c'}
>>> B - A
{'c'}

The set function requires a sequence as an argument. For the empty set use set() not {} as the latter is an empty dictionary. For more on dictionaries see the next section. There is a built-in length function, len(), which works for lists, strings, tuples, ranges, and sets.

>>> set('abc') - set('ac')
{'b'}
>>> set([1,2]).union(set([3,4]))
{1, 2, 3, 4}
>>> set()
set()
>>> len(range(10))
10
>>> len('abc')
3
>>> len((1,2))
2
>>> len(range(0,10,2))
5
>>> lst1 = [1,1,2,3,4]
>>> len(lst)
5
>>> set(lst)
{1, 2, 3, 4}
>>> len(set(lst)) # number of distinct elements in lst
4
>>> set(lst)
{1, 2, 3, 4}
>>> type({})
<class 'dict'>
>>> len(set())
0
>>> type(set())
<class 'set'>

Mapping Type

A Python dictionary maps keys to values. Dictionaries can be created by enclosing a comma-separated list of key: value pairs with braces. Values are called using the keys as arguments. Check out the following examples:

>>> dict1 = {'Jan': 1, 'Feb': 2, 'Mar': 3}
>>> dict1
{'Jan': 1, 'Feb': 2, 'Mar': 3}
>>> dict1['Mar']
3
>>> type(dict1)
<class 'dict'>
>>> type(dict1['Mar'])
<class 'int'>

String Methods

Pythons strings and lists have lots of built-in methods. It is a great idea to read through the Python documentation on built-in types to get familiar with them. Here we give some examples of a few:

  • lower()

  • upper()

  • capitalize()

  • sort()

  • isdigit()

  • isalpha()

  • append()

>>> 'Alex'.lower()
'alex'
>>> 'Alex'.upper()
'ALEX'
>>> 'alex'.capitalize()
'Alex'
>>> '100'.isdigit()
True
>>> '100'.isalpha()
False
>>> lst = [1, 2, 3]
>>> lst.append('a')
>>> lst
[1, 2, 3, 'a']
>>> lst = ['c', 'b', 'a']
>>> lst
['c', 'b', 'a']
>>> lst.sort()
>>> lst
['a', 'b', 'c']

Slicing strings and lists

Slices of strings can be removed with a syntax that looks like this: s[start, stop, step]. Here are a few examples:

>>> string = 'A Python string'
>>> string[2] # the indexing starts at 0
'P'
>>> string[2:8] # note that the slice ends on element 7
'Python'
>>> string[:8]
'A Python'
>>> string[2:]
'Python string'
>>> string[1:10:2]
' yhns'
>>> string[10:2:-2] # 2 steps back
't ot'
>>> string[::-1] # Reverses the string
'gnirts nohtyP A'
>>> lst = list('abcdefghijklmnopqrstuvwxyz')
>>> lst[0:5]
['a', 'b', 'c', 'd', 'e']
>>> lst[5:10]
['f', 'g', 'h', 'i', 'j']
>>> lst[9:4:-1]
['j', 'i', 'h', 'g', 'f']
>>> lst[::2]
['a', 'c', 'e', 'g', 'i', 'k', 'm', 'o', 'q', 's', 'u', 'w', 'y']