Introduction to Python

In this chapter, you will start testing your python by $\mathbf X$

  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 [1]:
#a = 2
#b = 1

a, b, c = 2, 3, "Hello World!"

In [2]:
#print a # works in python2 but not python3

print( a )


2

In [3]:
print ("Hello World!")


Hello World!

In [4]:
print (3*3)


9

In [5]:
print (3**2)


9

In [6]:
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 [7]:
myint = 7
myfloat1 = 7.0; myfloat2 = float(7)

You may separate commands using ";"


In [8]:
print (myint/2); print (myfloat1/2); print (myfloat2*2); print (myfloat2**2)


3.5
3.5
14.0
49.0

print myfloat1


In [1]:
mystring1 = 'Hello'

# in R mystring1 <- 'Hello'


mystring2 = "World"

In [2]:
mystring12 = mystring1+" "+mystring2+"!"+"?"+"!"
#add a comment

In [3]:
print (mystring12)


Hello World!?!

This is a box of comments

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 [4]:
dir()


Out[4]:
['In',
 'Out',
 '_',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_i3',
 '_i4',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'mystring1',
 'mystring12',
 'mystring2',
 'quit']

In [5]:
del mystring1, mystring2

In [6]:
dir()


Out[6]:
['In',
 'Out',
 '_',
 '_4',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__name__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_i6',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 '_sh',
 'exit',
 'get_ipython',
 'mystring12',
 'quit']

In [7]:
print (mystring12)


Hello World!?!

In [8]:
print (len(mystring12))


14

In [9]:
print (mystring12 * 2)


Hello World!?!Hello World!?!

In [11]:
print (3.0 / 2)
print (3 / 2.)
print (3 / 2)


1.5
1.5
1

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 [15]:
print (mystring12)
print (mystring12[0])


Hello World!?!
H

In [16]:
print (mystring12[1:2])
# 1:n [1:n]


e

In [32]:
print (mystring12[:])


Hello World!?!

In [33]:
mylist = [1, 2, 3.]
print (mylist)


[1, 2, 3.0]

In [35]:
print (mylist[0])


1

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


In [36]:
mylist = [1, 2, 3, "2", "Hello World", [1, 2, 3] ]

In [37]:
print (mylist)
print (mylist[-1])


[1, 2, 3, '2', 'Hello World', [1, 2, 3]]
[1, 2, 3]

In [39]:
print (mylist[2]*3)


9

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 [41]:
firstname= ["Mansoore","Shakib", "Mahdi","Somayeh"]
lastname=["Razmkhah", "Panah", "Alehdaghi","Noshadi"]

In [43]:
print (firstname)


['Mansoore', 'Shakib', 'Mahdi', 'Somayeh']

In [44]:
print (lastname)


['Razmkhah', 'Panah', 'Alehdaghi', 'Noshadi']

In [58]:
#The "zip" function pairs several lists of the same size.
firstlast = zip(firstname, lastname)
print (list(firstlast))


[('Mansoore', 'Razmkhah'), ('Shakib', 'Panah'), ('Mahdi', 'Alehdaghi'), ('Somayeh', 'Noshadi')]

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.


In [ ]:

Exercise
Add your new friend:

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

4. Conditions

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


In [61]:
x = 2
print (x == 2) 
print (x < 2)
print (not x < 2)


True
False
True

In [62]:
print( (x == 2)*(x > 1) )


1

In [73]:
a = 0
if a == 0:
    print( "a equals zero" ) # do not use a is equal to zero (bad English) 
else:  
    print( "a is non-zero" ) # do not use a is not equal to zero (bad English)


a equals zero

In [77]:
if x==2:
    print( "x equals two" )
else:
    print( "x differs" )


x equals two

In [ ]:

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 [79]:
print( firstname )
if "John" in firstname:
  print "John is in the list"


  File "<ipython-input-79-4e255f8659a8>", line 3
    print "John is in the list"
                              ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print(t "John is in the list")?

5. For Loop

The "for" loops iterate over a given sequence.
The "range" function is a very useful command in loops.


In [82]:
print( range(10) )
print( range(2,6) )
print( range(2,14,4) )


range(0, 10)
range(2, 6)
range(2, 14, 4)

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

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


range(0, 4)
Mansoore
Shakib
Mahdi
Somayeh

In [85]:
for name in firstname:
    print( name )


Mansoore
Shakib
Mahdi
Somayeh

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

6. Function definition

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


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

In [88]:
print( sq(75) )


5625

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


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

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


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

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

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


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