Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Introduction to:
Python and OpenSesame
What we’ve learned so far..
• Types (int,float,str,bool)
• Variables
• Functions (input -> blackbox -> output)
– Built-in
– Python Standard Library
•
•
•
•
2
Objects (blueprint -> instance)
Methods (Object’s functions)
Conditionals (if, elif, else, and, or..)
Script files (modules)
Intro to: Python and OpenSesame
Flow Control (Looping!)
X times
3
Command 1
Command 1
Command 2
Command 2
Command …
Command …
Last command
Last command
Intro to: Python and OpenSesame
For loop
for <iteration variable> in <iterator>:
<do something>
Iterator – a sequence of elements that we go over one at
a time
Iteration variable – the variable that holds the current
element in the loop
4
Intro to: Python and OpenSesame
For loop
Example:
Iteration Variable
>> for i in (1,2,3,4):
>> print ‘beep’ * i
Iterator (type tuple)
i = 1 -> ‘beep’
i = 2 -> ‘beepbeep’
i = 3 -> ‘beepbeepbeep’
i = 4 -> ‘beepbeepbeepbeep’
5
Intro to: Python and OpenSesame
Example – Stairway to heaven
Let’s Create stairs with Turtle:
What would be the steps?
1. Change the starting position to the top of the screen
2. Examine these steps:
1.
2.
3.
4.
5.
6.
7.
First turn right, 90 degrees
Then Forward, some steps
Then turn left, 90 degrees
Turn forward, some steps
First turn right, 90 degrees
Then Forward, some steps
Then turn left, 90 degrees
A classic case for a “FOR” loop
6
Intro to: Python and OpenSesame
Example
What would the for loop do?
We keep repeating a pair of
instructions.
But we alternate the direction of the
first.
Repeat:
turn right/left
move forward
7
1.
2.
3.
4.
5.
6.
7.
8.
Intro to: Python and OpenSesame
First turn right, 90 degrees
Then Forward, some steps
Then turn left, 90 degrees
Turn forward, some steps
First turn right, 90 degrees
Then Forward, some steps
Then turn left, 90 degrees
Then Forward, some steps
Example
We can use an if statement to control the alternation of
the direction command.
Repeat:
if <sometime>:
turn right
elif <something else>:
turn left
move forward
8
What would be the
condition?
Intro to: Python and OpenSesame
Example
When we use a for loop, we iterate over a sequence of
objects. We can use the range() function to create a list
of numbers to iterate on:
>> range(1,11) = [1,2,3,4,5,...9,10]
[Include, exclude]
In every iteration, our iteration variable will be equal to
a number in the list (in order).
To alternate the directions, we can use the parity
condition of the iteration variable!
9
Intro to: Python and OpenSesame
Example
1
2
3
4
5
6
7
8
9
odd
even
odd
even
odd
even
odd
even
…
10
We can use the module (%) if i % 2 != 0:
if i is odd:
operator for that:
turn right
turn right
elif i is even:
elif i % 2 == 0:
turn left
turn left
the modulo operation finds the remainder after division of
one number by another
[http://en.wikipedia.org/wiki/Modulo_operation]
10
Intro to: Python and OpenSesame
Example
stairs.py
11
Intro to: Python and OpenSesame
While loop
while <this == True>:
<do something>
A loop – but without
an iterator or
iteration variable
We’re using conditions just like the “if”
statements
Example:
12
i=1
while i < 15:
print i
i += 1
Intro to: Python and OpenSesame
Counter
A new way of writing
i=i+1
While loop
Imagine the horror:
>> i = 1
>> while i > 0:
>> print ‘evil laughter’
>> i+=1
This will always be
true!
An infinite loop!
As we have no way of stopping this evil program. Our
only escape is to crash it (using our ctrl+c gun)…
13
Intro to: Python and OpenSesame
While loop
In our previous example, we saw that we have no way out.
But we can still do something..
A mighty hero will rise to free us and break the chains of the infinite loop.
>> i = 0
>> while i > 0:
>>
print ‘evil laughter’
>>
i+=1
>>
if i == 15:
>>
break
14
Break will slay the
vicious loop
Intro to: Python and OpenSesame
Nested Loops
Python allows for us to use loops inside loops.
Recall that we need to use indented blocks for
the inner loop.
Let’s see a cool example [double spiral!].
15
Intro to: Python and OpenSesame
Homework~ (Do it at home or later)
In a new script file (circsquare.py)
• Use a while loop to draw this figure
(this is a circle made out of squares)
16
Intro to: Python and OpenSesame
Create a function!
Now that we know how functions work, we should
learn how to create functions of our own.
def function(<input>):
<black box>
return <output>
17
Syntax
Intro to: Python and OpenSesame
Create a function!
Lets write an addition function, we’ll call it addition.
The function takes two numbers then adds them and
returns their sum.
def addition(x,y):
sum = x+y
return sum
Save the script file as:
add.py
We should add information about the expected input and
output of this function, we’ll use docstrings for that.
18
Intro to: Python and OpenSesame
Docstrings
We don’t really need the sum =
x+y step.. We can just return the
value of the addition
Docstrings are multiline strings, placed at the head of
the function. This information will be seen when using
the help function.
>> help(addition)
19
Intro to: Python and OpenSesame
Using your own modules
We saw that we can import functions and objects from
the Python Standard Library.
If we create functions of our own and save them in
script files (modules), we can import them to other
scripts the same way.
20
Intro to: Python and OpenSesame
Using your own modules
We saved our addition() function in the script: add.py
add.py is in fact a module, which we can import!
Create a new python script called mathy.py and save it
in the same folder as add.py.
21
Intro to: Python and OpenSesame
Using your own modules
mathy.py
Python Interpreter
22
Intro to: Python and OpenSesame
Let’s test our addition() function
•
•
•
•
What happens if we use two ints?
What happens if we use two floats?
What happens if we use an int and a float?
What happens if we use two strings?
We wanted addition() to compute the sum of two numbers,
not add {concatenate} two strings!
What can we do to make sure the function does what we
want it to do?
23
Intro to: Python and OpenSesame
Understanding Python Errors
Sometimes you will write a piece of code, and
get a nasty red error. Here are some common
ones:
• SyntaxError - You misspelled / misused a
Python command
– fer i in range(1,10):
• IndentationError – You created a blocked code
but didn’t indent it correctly.
24
Intro to: Python and OpenSesame
Understanding Python Errors
• TypeError – When using a function on the wrong
input type.
• ImportError – Can’t find the module you are
trying to import (not in the PSL or in the folder).
• NameError – A variable you’re using can’t be
found.
– while i < 10:
25
Intro to: Python and OpenSesame
Let’s test our addition() function
We saw that our addition() function had different
outputs to different input types.
As the developers of the addition() function, we should
notify the user of an error if he’s misusing our function.
This is done with the raise keyword.
26
Intro to: Python and OpenSesame
Addition(s) with conditions
raise TypeError tells python to crash
the program because an error has
occurred. This error specifically tells
the user that he’s using the wrong
data types for the function.
27
Intro to: Python and OpenSesame
More on functions
Not all functions need a return statement..
For example
Validating our function:
Here too, we better make sure that
we input a word and not a number
or a string with digits because it
does not make sense…
we have str methods for that.
28
Intro to: Python and OpenSesame
More Data Types (the list goes on..)
List
a container that holds a number of objects
– in a specific order.
>> x = [1, 2, 3, 4]
>> y = [1, 2.0, ’3’, ”four”]
29
Python creates a list with
[SQUARE BRACKETS]
Intro to: Python and OpenSesame
Lists
Accessing a specific element in the list:
>> x = [‘a’, ’b’, ’c’, ’d’]
>> x[1]
‘b’
?!?!
Python counts arrays indices from 0, not 1.
30
Object
‘a’
‘b’
‘c’
‘d’
Index
0
1
2
3
Intro to: Python and OpenSesame
Lists
Object
‘a’
‘b’
‘c’
‘d’
Index
0
1
2
3
Accessing a specific element in the list:
>> x = [‘a’, ’b’, ’c’, ’d’]
>> x[0]
‘a’
>> x[-1]
‘d’
>> x[-2]
=?
We can ask for part of the list
>> x[1:2]
** Like the range() function we
mentioned earlier, the range is
‘b’
from<inclusive> to<exclusive>
31
Intro to: Python and OpenSesame
Lists
Object
‘a’
‘b’
‘c’
‘d’
Index
0
1
2
3
>> x = [‘a’, ’b’, ’c’, ’d’]
>> x[0:2]
[‘a’, ’b’]
>> x[2:] # from 2 to the end
[‘c’, ’d’]
>> x[:1]
=?
We can change the steps
>> x[0:-1:2]
[‘a’, ’c’]
pop quiz: how do we get the reversed list?
32
Intro to: Python and OpenSesame
Understanding Python Errors
• IndexError – Trying to access an index of a list,
but the list is shorter.
– x = [1, 2, 3]
– x[3]
33
Intro to: Python and OpenSesame
Lists
Lists are mutable. This means we can change their content.
>> x = [1, 2, 3, 4]
>> x[0]
1
>> x[1] = ‘one’
>> x = [1,’one’,3,4]
This is in contrast to other types that are immutable:
>> x = ‘hello’
>> x[0]
Recall TypeError
‘h’
>> x[1] = ‘y’
TypeError: 'str' object does not support item assignment
34
Intro to: Python and OpenSesame
Lists
We can join two lists together using the + operator:
>> [1, 2] + [3, 4]
[1, 2, 3, 4]
Or multiply a list with the * operator:
>> [‘a’, ’b’] * 3
[‘a’, ’b’, ’a’, ’b’, ’a’, ’b’]
35
Intro to: Python and OpenSesame
Lists - Methods
We can see the methods the list object has with help(list)
Some examples:
>> L = [2, 1, 4, 3]
>> L.sort()
>> L
[1, 2, 3, 4]
Sorting
36
>> L = [‘a’, ’b’, ’c’, ’d’]
>> L.append(‘e’)
>> L
[‘a’, ’b’, ’c’, ’d’, ’e’]
Appending
Intro to: Python and OpenSesame
>> L = [‘a’, ’b’, ’c’, ’d’]
>> L.pop()
‘d’
>> L
[‘a’, ’b’, ’c’]
Removing
Elements
Time for a python program
Write a function that takes as input a number.
When called, the function’s output is drawing with turtle a squared spiral that
uses the input number as its starting size reference.
Start size
Implementation advice:
• You will need to use a loop, but here, the size keeps getting
smaller. How would you implement that?
** Bonus points – change the color of the line after every corner (randomly…)
Tips – work with the standard library on-line help
(type “python turtle” in Google).
37
Intro to: Python and OpenSesame
Tuples
Tuples are immutable, ordered sequences of objects.
>> x = (1, ’two’, 3.0)
>> x[1]
‘two’
>> x[1] = ‘a’
TypeError: 'tuple' object does not support item assignment
38
Intro to: Python and OpenSesame
Tuples
Tuples are great for sending a bulk of variables, and also,
receiving a bulk of variables, for example from a function.
This is called Tuple
Unpacking
>> a = minmax([1, 2, 3, 4])
>> a[0]
1
>> a[1]
4
39
>> (a, b) = minmax([1, 2, 3, 4])
>> a
1
>> b
4
Intro to: Python and OpenSesame
String comprehension
We can use operator to create more advanced strings,
these are very useful when we try create strings that
involve information from variables.
The following is a good example for something we will
often do with OpenSesame:
40
Intro to: Python and OpenSesame
String comprehension
>> items = [‘one’, ’two’, ’three’, ’four’] # assume these are stimuli
for the experiment…
>> for item in items:
>>
picture = items + ‘.jpg’
>>
…some function that loads the picture file…
Folder:
1
2
3
one.jpg two.jpg three.jpg
41
Intro to: Python and OpenSesame
Iterators
Many objects can serve as iterators (recall for loops)
t = (‘lion’, ‘giraffe’, ‘monkey’, ‘turtle’)
l = [(‘yoni’,12345),(‘kobi’,41235),(‘dana’,53829)]
S = “kingofrock”
Let’s count the indices and our animals…
42
Intro to: Python and OpenSesame
Iterators
t = (‘lion’, ‘giraffe’, ‘monkey’, ‘turtle’)
Focus on the elements
for animal in t:
print “The animal at index:”, t.index(animal), ”is a”, animal
Focus on the index
for i in range(0,len(t)):
print “The animal at index:”, i, ”is a”, t[i]
Why not both?
for pair in enumerate(t):
print “The animal at index:”, pair[0], ”is a”, pair[1]
43
Intro to: Python and OpenSesame
Iterators
A list holding tuples!
l = [(‘yoni’, 12345), (‘kobi’, 41235), (‘dana’, 53829)]
for pair in l:
print pair[0]+”’s”,”phone number is:”,pair[1]
We can even double loop using the list as outer loop
and the tuple as inner loop.
44
Intro to: Python and OpenSesame
Iterators
s = “kingofrock”
A string!
for letter in s:
print letter.upper()
45
Intro to: Python and OpenSesame
Wrap Up
Python can do much more. And it has a lot
more features.
The last two sessions gave you a quick overview
of the language, it’s syntax and data types.
46
Intro to: Python and OpenSesame
Wrap Up
The knowledge you’ve accumulated so far will
definitely help you create and program
experiments with OpenSesame.
If you feel like learning more, I suggest following
one or more of the following tutorials and
courses.
47
Intro to: Python and OpenSesame
Wrap Up
•
•
•
•
48
http://learnpythonthehardway.org/book/
http://ocw.mit.edu/courses/electrical-engineering-and-computerscience/6-00sc-introduction-to-computer-science-and-programmingspring-2011/index.htm
https://www.udacity.com/course/intro-to-computer-science--cs101
https://www.udacity.com/course/programming-foundations-withpython--ud036
Intro to: Python and OpenSesame