Python Syntax List String
Python Syntax List String
20
for loops and range()
• for always iterates through a list or sequence
>>> sum = 0
>>> for i in range(10):
... sum += i
... Java 1.5
>>> print sum foreach (String word : words)
! System.out.println(word)
45
23
if ... elif ... else
>>> a = "foo"
>>> if a in ["blue", "yellow", "red"]:
... print a + " is a color"
... else:
...! ! if a in ["US", "China"]:
... ! ! print a + " is a country"
... ! ! else:
...! ! ! ! print "I don't know what”, a, “is!"
...
I don't know what foo is! switch (a) {
! case “blue”:
>>> if a in ...: ! case “yellow”:
! case “red”:
... print ... C/Java ! ! print ...; break;
... elif a in ...: ! case “US”:
! case “China”:
... print ... ! ! print ...; break;
... else: ! else:
... print ... !
}
! print ...;
24
! !
break, continue and else
• break and continue borrowed from C/Java
• special else in loops
• when loop terminated normally (i.e., not by break)
• very handy in testing a set of properties|| func(n)
>>> add(1,1)
error!
>>> add(add(1))
[[1]] lists are heterogenous!
28
Approaches to Typing
✓ strongly typed: types are strictly enforced. no implicit
type conversion
- weakly typed: not strictly enforced
- statically typed: type-checking done at compile-time
✓ dynamically typed: types are inferred at runtime
weak strong
static C, C++ Java, Pascal
>>> a[:]
[1, 'python', [2, '4']]
31
+, extend, +=, append
• extend (+=) and append mutates the list!
>>> a.append('5')
>>> a
[1, 'python', [2, '4'], 2, 3, '5']
>>> a[2].append('xtra')
>>> a
[1, 'python', [2, '4', 'xtra'], 2, 3, '5']
32
Comparison and Reference
• as in Java, comparing built-in types is by value
• by contrast, comparing objects is by reference
>>> c = b [:]
>>> [1, '2'] == [1, '2'] >>> c
True [1, 5]
>>> a = b = [1, '2'] >>> c == b slicing gets
>>> a == b
True a shallow copy
>>> c is b
True False
>>> a is b
True >>> b[:0] = [2] insertion
>>> b
>>> b [1] = 5
[2, 1, 5]
>>> a
>>> b[1:3]=[]
[1, 5] >>> b deletion
>>> a = 4 [2]
>>> b a += b means
>>> a = b
[1, 5] a.extend(b)
>>> b += [1]
>>> a is b >>> a is b NOT
>>> False True a = a + b !!
33
List Comprehension
>>> a = [1, 5, 2, 3, 4 , 6]
>>> [x*2 for x in a]
[2, 10, 4, 6, 8, 12]
>>> [x for x in a if \
4th smallest element
... len( [y for y in a if y < x] ) == 3 ]
[4]
>>> a = range(2,10)
>>> [x*x for x in a if \
... [y for y in a if y < x and (x % y == 0)] == [] ]
???
[4, 9, 25, 49] square of prime numbers
34
List Comprehensions
>>> vec = [2, 4, 6]
>>> [[x,x**2] for x in vec]
[[2, 4], [4, 16], [6, 36]]
sequence of characters
Basic String Operations
• join, split, strip
• upper(), lower()
http://docs.python.org/lib/string-methods.html 37
Basic Search/Replace in String
>>> "this is a course".find("is")
2
>>> "this is a course".find("is a")
5
>>> "this is a course".find("is at")
-1
39