Introduction to Python

In this chapter, you will start testing your python by

  1. printing basic operations,
  2. defining different variable types,
  3. looking into lists of objects,
  4. making decisions with conditions,
  5. iterating with for loops and
  6. defining some basic functions.

1. Basic Syntax


In [2]:
a, b, c = 2, 3, "Hello World!"

In [3]:
print a, b, c


2 3 Hello World!

In [4]:
print "Hello World!"


Hello World!

In [5]:
print 3*3


9

In [6]:
print 3**2


9

In [7]:
print 2+2


4

You can find more examples at LearnPython & PythonTutorial.

2. Variable Types

You are automatically defining a variable type while initializing the variable such as


In [8]:
myint = 7
myfloat1 = 7.0; myfloat2 = float(7)

You may separate commands using ";"


In [9]:
print myint/2; print myfloat1/2; print myfloat2*2; print myfloat2**2


3
3.5
14.0
49.0

In [10]:
print myfloat1


7.0

In [11]:
mystring1 = 'Hello'
mystring2 = "World"
mystring12 = mystring1+" "+mystring2+"!"

You may define strings differently, and attach them using "+". You can remove a variable from the memory when you do not need, using "del"


In [12]:
del mystring1, mystring2;

In [13]:
dir()


Out[13]:
['In',
 'Out',
 '_',
 '_1',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '_dh',
 '_i',
 '_i1',
 '_i10',
 '_i11',
 '_i12',
 '_i13',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_i7',
 '_i8',
 '_i9',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'a',
 'b',
 'c',
 'exit',
 'get_ipython',
 'myfloat1',
 'myfloat2',
 'myint',
 'mystring12',
 'quit']

In [14]:
print mystring12


Hello World!

In [15]:
print len(mystring12)


12

In [16]:
print mystring12 * 2


Hello World!Hello World!

3. Lists

List a special case of array, except they can include variables with different types. You can easily append, delete, merge, different lists. You can even exchange the index number with a string as a name. List is one of the most useful objects in Python.

Index in list starts from zero (0) unlike R. A string is actually a list. -1 shows the end of the list but the last. Range of indices is like [start, end[ so you do not get access to the last element.


In [17]:
print mystring12[-1:]


!

In [18]:
print mystring12[0:-1]


Hello World

In [19]:
print mystring12[:]


Hello World!

In [20]:
mylist = [1,2,3]
print mylist


[1, 2, 3]

In [21]:
print mylist[0]


1

Here is a simple example that shows how a list is different with an array.


In [1]:
mylist=[1,2,3,"2", "HelloWorld", [1,2,3] ]

In [5]:
print mylist
print mylist[-1]


[1, 2, 3, '2', 'HelloWorld', [1, 2, 3]]
[1, 2, 3]

In [24]:
print mylist[-1]*3


[1, 2, 3, 1, 2, 3, 1, 2, 3]

The "zip" function pairs several lists of the same size.

Exercise

Make two lists. First, a list of 4 of your best friends' first name.

Second, a list of their family name. Then print their first name and last name.


In [25]:
firstname= ["John","Bruno", "Alan","Ali"]
lastname=["Smith", "Agard", "Turing","Bendavid"]

In [26]:
print firstname


['John', 'Bruno', 'Alan', 'Ali']

In [27]:
print lastname


['Smith', 'Agard', 'Turing', 'Bendavid']

In [28]:
print zip(firstname,lastname)


[('John', 'Smith'), ('Bruno', 'Agard'), ('Alan', 'Turing'), ('Ali', 'Bendavid')]

You may insert several other elements to the list using "append", "insert", "index" and several others. See below for for more details

list.append(x)

Add an item to the end of the list; equivalent to a[len(a):] = [x].

list.extend(L)

Extend the list by appending all the items in the given list; equivalent to a[len(a):] = L.

list.insert(i, x)

Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).

list.remove(x)

Remove the first item from the list whose value is x. It is an error if there is no such item.

list.pop([i])

Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)

list.index(x)

Return the index in the list of the first item whose value is x. It is an error if there is no such item.

list.count(x)

Return the number of times x appears in the list.

list.sort(cmp=None, key=None, reverse=False)

Sort the items of the list in place (the arguments can be used for sort customization, see sorted() for their explanation).

list.reverse()

Reverse the elements of the list, in place.

Exercise
Add your new friend:

  1. As the first element,
  2. as the last element,
  3. in the middle.

In [29]:
firstname.insert(2,"Martin")
print firstname


['John', 'Bruno', 'Martin', 'Alan', 'Ali']

In [30]:
lastname.insert(2,"Trepanier")
print lastname


['Smith', 'Agard', 'Trepanier', 'Turing', 'Bendavid']

4. Conditions

Python uses boolean variables to evaluate conditions. Tab separates different code blocks, therefore there is no need for brackets.


In [31]:
x = 2
print x == 2 
print x<2
print not x<2


True
False
True

In [32]:
if x==2:
    print "x equals to two"
else:
    print "print x differs from two"


x equals to two

In [33]:
#a=1
#if a==1:
#print "ye ye a equals to one"
#else:
#print "nop a differs from one"

Lines and Indentation

Python provides no braces to indicate blocks of code for class and function definitions or flow control. Blocks of code are denoted by line indentation, which is rigidly enforced.

The number of spaces in the indentation is variable, but all statements within the block must be indented the same amount.


In [34]:
print firstname
if "John" in firstname:
    print "John is in the list"


['John', 'Bruno', 'Martin', 'Alan', 'Ali']
John is in the list

5. For Loop

The "for" loops iterate over a given sequence.


In [35]:
print range(len(firstname))

for i in range(len(firstname)):
    print firstname[i]


[0, 1, 2, 3, 4]
John
Bruno
Martin
Alan
Ali

In [36]:
for name in firstname:
    print name


John
Bruno
Martin
Alan
Ali

Exercise
Create a new list in the form of firstname_lastname of your 5 friends.


In [37]:
first_last=[""]*len(firstname)
print first_last
for i in range(len(firstname)):
    first_last[i]=firstname[i]+"_"+lastname[i]
print first_last


['', '', '', '', '']
['John_Smith', 'Bruno_Agard', 'Martin_Trepanier', 'Alan_Turing', 'Ali_Bendavid']

In [38]:
for name, family in zip (firstname, lastname):
    print name+"_"+family


John_Smith
Bruno_Agard
Martin_Trepanier
Alan_Turing
Ali_Bendavid

The "range" function is a very useful command in loops.


In [39]:
print range(6)


[0, 1, 2, 3, 4, 5]

In [40]:
print range(2,6)


[2, 3, 4, 5]

In [41]:
print range(2,14,4)


[2, 6, 10]

6. Function definition

The "def" command, can be used to define a function.


In [42]:
def sq(x):
    return x**2

In [43]:
print sq(4)


16

Exercise
Define a function that gives the square of a list elements.


In [44]:
def sqlist1(X):
    return [sq(x) for x in X]

In [45]:
sqlist1(range(6))


Out[45]:
[0, 1, 4, 9, 16, 25]

In [46]:
def sqlist2(X):
    Y=[0]*len(X)
    for i in range(len(X)): 
        Y[i]=sq(X[i])
    return Y

In [47]:
sqlist2(range(6))


Out[47]:
[0, 1, 4, 9, 16, 25]