Agenda

  • Control flows

  • Functions

  • Data structures

  • Modules

Python at a glance

  • A sample code from C

    for (int i = 0; i <= 6; i++) {
        if (i % 2 == 0) {
            printf("Even number: %d\n", i);
        }
    }

  • A sample code from Python

In [1]:
for number in [0, 1, 2, 3, 4, 5, 6]:
    if number % 2 == 0:
        print "Even number:", number


Even number: 0
Even number: 2
Even number: 4
Even number: 6

What do we see?

  • No semicolon
  • No parenthese () or brackets {}
  • Wait... How do we express code block like in C?
    • Using indentation
  • No static typing

Basic of Python

Number

Expression syntax and the operators: +, -, *, %, / work just like in most other languages.


In [2]:
(50 - 5.0 * 6) / 4


Out[2]:
5.0

** operator can be used to calculate powers


In [3]:
5 ** 2


Out[3]:
25

String

  • Enclosed in single quotes '...' or double quotes "...".

  • \ can be used to escape characters


In [4]:
"I can eat glass it doesn't hurt me"


Out[4]:
"I can eat glass it doesn't hurt me"

In [5]:
'I can eat glass it doesn\'t hurt me'


Out[5]:
"I can eat glass it doesn't hurt me"
  • Print a string using print statement.
  • If you don’t want characters prefaced by \ to be interpreted as special characters, you can use raw strings by adding an r before the first quote

In [6]:
print 'I can eat glass.\nIt doesn\'t hurt me'
print '---------------'
print r'I can eat glass.\n It doesn\'t hurt me'


I can eat glass.
It doesn't hurt me
---------------
I can eat glass.\n It doesn\'t hurt me
  • String literals can span multiple lines using triple-quotes: """...""" or '''...'''

In [7]:
print '''I can eat glass
It doesn't hurt me'''


I can eat glass
It doesn't hurt me
  • Concatenate string using +
  • Repeat a string using *

In [8]:
print 'AA' + 'BB'
print 'AA' * 3


AABB
AAAAAA
  • Access a character in string using index, first index is 0
  • Indices may also be negative numbers, to start counting from the right

In [9]:
word = 'python'
print word[0]
print word[-1]
print word[-2]


p
n
o
  • Slicing is also supported.

In [10]:
#  Get characters from position 1 to position 4 (4 characters)
print word[1:5] # exclude 5
# Get characters from position 1 to the end
print word[1:]
# Get all characters except the final character
print word[:-1]
# Get 3 last characters
print word[-3:]


ytho
ython
pytho
hon
  • Python strings cannot be changed - they are immutable

In [11]:
# get error when trying to change 
word[0] = 'J'


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-31dcbf8b41b8> in <module>()
      1 # get error when trying to change
----> 2 word[0] = 'J'

TypeError: 'str' object does not support item assignment
  • But if you need a different string, you can create a new one

In [12]:
print 'J' + word[1:]


Jython
  • len() function can be used to calculate length of string

In [13]:
print len(word)


6

List

  • You can think it as array.
  • Can be defined as list of comma-separated values between square brackets
  • Might contain items of different types.

In [14]:
squares = [1, 4, 9, 16, 25]
print squares


[1, 4, 9, 16, 25]
  • Like strings (and all other built-in sequence types), list can be indexed and sliced:

In [15]:
print squares[0] # Indexing returns the item


1

In [16]:
print squares[-1]


25

In [17]:
print squares[-3:] # Slicing returns a new list


[9, 16, 25]
  • However, unlike strings, list are mutable type. It is possible to change their content

In [18]:
cubes = [1, 8, 27, 65, 125] # something's wrong here
print cubes


[1, 8, 27, 65, 125]

In [19]:
cubes[3] = 64
print cubes


[1, 8, 27, 64, 125]
  • Concatenate lists using + operator
  • Add new items at the end of the list by using append() method
  • Calculate length of list using len() function

In [20]:
print squares + [36, 49]


[1, 4, 9, 16, 25, 36, 49]

In [21]:
squares.append(36)
print squares


[1, 4, 9, 16, 25, 36]

In [22]:
print len(squares)


6
  • Assignment to slices is also possible
    • It can change the size of the list

In [2]:
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
print letters


['a', 'b', 'c', 'd', 'e', 'f', 'g']

In [3]:
letters[2:5] = ['C', 'D', 'E']
print letters


['a', 'b', 'C', 'D', 'E', 'f', 'g']

In [4]:
letters[2:5] = ['-']
print letters


['a', 'b', '-', 'f', 'g']

Unpacking

Unpack a sequence to the variables


In [37]:
a, b, c = [1, 2, 3]
print a, b, c


1 2 3
  • Number of variables and length of sequence must match

In [36]:
a, b, c = [1, 2]


---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-9d4181223c7f> in <module>()
----> 1 a, b, c = [1, 2]

ValueError: need more than 2 values to unpack

In [39]:
a, b = 1, 2
a, b = b, a
print a, b


2 1