6 minute read

This first Python tutorial will cover the basic types and operations that form the building blocks of the Python syntax. These types in Python can be defined as:

  • Strings
  • Numbers
  • Lists
  • Dictionaries
  • Tuples
  • Files

 

Strings

  • Strings assume a positional ordering among items
  • You can verify the length of a string with the built in function len()
  • You can fetch components of a string with X[position]
>>> s='Spam'
>>> len(s)
4
>>> s[0]
'S'
>>> s[1]
'p'

You can also use slicing to extract a piece of a string. Slicing extracts a section of a string instead of an individual character.

>>> s[1:3]
'pa'

This general form X[I:J] means “give me everything in X from offset I up to but NOT including offset J.”

In a slice, the left bound defaults to zero, and the right bound defaults to the length of the string.

>>> s[1:]
'pam'
>>> s[:3]
'Spa'
>>> s[:-1]                     #Everything but the last character
'Spa'

Strings support repetition and concatenation

>>> s+'xyz'       #Concatenation
'Spamxyz'
>>> s*8           #Repetition
'SpamSpamSpamSpamSpamSpamSpamSpam'

Notice that the plus sign (+) and asterisk (*) do different things for different objects, for strings they represent concatenation and repetition, for numbers they represent addition and multiplication. This is a general property of Python called Polymorphism which will be discussed later on.

Also notice that in these previous operations we did not change the original string; that’s because strings are immutable– They cannot be changed after they are created. Every string operation is defined to produce a new string as its result.

>>> s[0] = 'z'
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: 'str' object does not support item assignment

To embed a quote in a string, you can “escape” the quote with a backslash.

>>> 'knight\'s'
"knight's"

An escape sequence always begins with a backslash followed by a character that represents what you would like to do. For example, “\n” is a new line “\t” is a horizontal tab and “\’” is an apostrophe.

To convert a string to a number and a number to a string you must use conversion tools, specifically, int() and str().

>>> s= '42'
>>> i=1
>>> s+i
Traceback (most recent call last):
  File "<console>", line 1, in <module>
TypeError: cannot concatenate 'str' and 'int' objects

If you try and add a string and an integer together you get the error above.

>>> int(s) + i
43
>>> s + str(i)
'421'

If you convert s to an integer then the plus sign performs addition giving the sum 43. Conversely, if you convert i to a string then the plus sign concatenates the string to ‘421’.

 

Numbers

Python supports the standard object types for numbers: integers (whole numbers), floating-point numbers (include decimal point), as well as several more obscure types (long numbers, fixed precision…)

Python supports the standard mathematical operations: +, – , *, /, and ** for exponent.

>>> 123 + 222
345
>>> 1.5 *4
6.0
>>> 8 / 4
2
>>> 2 ** 100
1267650600228229401496703205376L

The “L” at the end of the last number represents Python converting up to a long integer format to try and provide extra precision.

 

Lists

In Python, Lists are “positionally ordered collections of arbitrarily typed objects, and they have no fixed size.”  Unlike strings, Lists are mutable; they can be modified in-place by assignment to offsets. Lists are characterized by brackets with each list item separated by a comma.

>>> L = [123, 'spam', 1.23]
>>> len(L)
3

We can perform a lot of the same actions on lists as strings. i.e. index, slice, concatenate…

>>> L[0]
123
>>> L[:-1]
[123, 'spam']
>>> L2 = L + [4,5,6]          #Concatenation makes a new list
>>> L2
[123, 'spam', 1.23, 4, 5, 6]
>>> L                         #The original list stays the same
[123, 'spam', 1.23]

If we want to add another list item to a list, we have to use append() to automatically add a list item to the end of the current list.

>>> L.append('hello world')
>>> L
[123, 'spam', 1.23, 'hello world']

Other list operations include sort() (sorts list alphabetically), reverse() (reverses the order of the list), and pop() (removes a list item at a certain index)

>>> L.sort()
>>> L
[1.23, 123, 'hello world', 'spam']
>>> L.reverse()
>>> L
['spam', 'hello world', 123, 1.23]
>>> L.pop(2)
123
>>> L
['spam', 'hello world', 1.23]

Lists also support nesting which allows Lists to be used to represent multi-dimensional matrices.

>>> M = [[1,2,3],[4,5,6],[7,8,9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> M[1]
[4, 5, 6]
>>> M[1][0]
4

 

Dictionaries

Up to this point the object types we have learned about have been sequences because they index from left to right. When you want to look at a specific instance in a sequence you call it by its position in the index. Dictionaries are the only core Python object that are not sequences; Dictionaries are known as mappings because they map a key to a value in a Dictionary.

>>> D = {'food':'Spam', 'quantity':4, 'color':'pink'}
>>> D
{'food': 'Spam', 'color': 'pink', 'quantity': 4}
>>> D['food']
'Spam'

Notice that a Dictionary is syntactically notated with curly braces and key-value pairs with a colon in between.

With Dictionaries it is good practice to perform an audit check on the existence of a key before performing an action on that key. This will prevent an ugly system error and instead, provide a Boolean true or false. This can be done with the built-in function, has_key().

>>> D['person']
Traceback (most recent call last):
  File "<console>", line 1, in <module>
KeyError: 'person'
>>> D.has_key('person')
False
>>> D.has_key('food')
True

Alternatively, using the  get()  function allows you to set a default answer  if the key does not exist.

>>> D.get('food')
'meatloaf'
>>> D.get('person', 'Albert')
'Albert'

Dictionaries also use the same pop() function as lists to delete a key-value pair, the only difference is that you provide a key to delete instead of an index location.

>>> D
{'food': 'meatloaf', 'snack': 'pretzel'}
>>> D.pop('snack')
'pretzel'
>>> D
{'food': 'meatloaf'}

 

Tuples

Tuples (pronounces “tuhple” or “toople”) are exactly like a list except they are immutable, they cannot be changed. They are created syntactically with parenthesis instead of brackets and are only useful if you need to pass information that must remain constant, for data integrity.

>>> L = [1,2,3,4]       #Mutable List
>>> L
[1, 2, 3, 4]
>>> L[0] = 8            #Changed the first occurrence to an 8
>>> L
[8, 2, 3, 4]
>>> T = (1,2,3,4)       #Immutable Tuple
>>> T
(1, 2, 3, 4)
>>> T[0] = 8            #Get error when trying to change values
Traceback (most recent call last):
File "<console>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

 

Files

File objects are Python’s main interface to external files on your computer. There is no specific literal syntax to call a File object, instead you use the built in function open(). When calling this function you pass 2 things, the filename and the action to perform on that file.

>>> f = open('ex1.txt', 'w')        #’w’ is the action to open the file in
>>> f.write('Hello')                #write-mode
>>> f.write('World')
>>> f.close()
>>> f = open('ex1.txt', 'r')        #’r’ is the action to open the file in
>>> bytes = f.read()                #read mode, it is the default if left
>>> bytes                           #blank
'HelloWorld'
>>> print bytes
HelloWorld

 

Exercises

  1. Define a string ‘S’ of four characters where S = ‘spam’. Write an assignment that changes the string to ‘slam’, using only slicing and concatenation.
  2. Make a dictionary with key-value pairs for your first and last name, your favorite color, a hobby you enjoy, and your favorite food. Then write your dictionary to a new text document (.txt) called “myInfo” in the following format:

My Info
First Name: Blah
Last Name: Maxwell
Favorite Color: Green
Hobby: Eating snow
Favorite food: Anchovies

 

Next Up

Once you have a firm understanding of Python Types & Operations, Proceed to Part 2 of this Python tutorial: Statements, Syntax & Functions.