Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Python Syntax List String

Python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Python Syntax List String

Python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Basic Python Syntax

Numbers and Strings


• like Java, Python has built-in (atomic) types
• numbers (int, float), bool, string, list, etc.
• numeric operators: + - * / ** %
>>> a = 5 >>> c = 1.5 >>> s = “hey”
>>> b = 3 >>> 5/2 >>> s + “ guys”
>>> type (5) 2 'hey guys'
<type 'int'> >>> 5/2. >>> len(s)
>>> a += 4 2.5 3
>>> a >>> 5 ** 2 >>> s[0]
9 25 'h'
no i++ or ++i >>> s[-1]
>>> from __future__ import division 'y'
>>> 5/2
2.5 recommended!
19
Assignments and Comparisons
>>> a = b = 0 >>> a = b = 0
>>> a >>> a == b
0 True
>>> b >>> type (3 == 5)
0 <type 'bool'>
>>> "my" == 'my'
>>> a, b = 3, 5 True
>>> a + b
8 >>> (1, 2) == (1, 2)
>>> (a, b) = (3, 5) True
>>> a + b
>>> 8 >>> 1, 2 == 1, 2
>>> a, b = b, a ???
(swap) (1, False, 2)

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

>>> for word in ["welcome", "to", "python"]:


... print word,
...
welcome to python

>>> range(5), range(4,6), range(1,7,2)


([0, 1, 2, 3, 4], [4, 5], [1, 3, 5])
21
while loops
• very similar to while in Java and C
• but be careful
• in behaves differently in for and while
• break statement, same as in Java/C
>>> a, b = 0, 1
>>> while b <= 5:
... print b
... a, b = b, a+b
...
1 simultaneous
1 assignment
2
3 fibonacci series
5
22
Conditionals
>>> if x < 10 and x >= 0:
>>> if 4 > 5:
... print x, "is a digit"
... print "foo"
...
... else:
>>> False and False or True
... print "bar"
True
...
>>> not True
bar
False

>>> print “foo” if 4 > 5 else “bar”


...
conditional expr since Python 2.5
>>> bar

C/Java printf( (4>5)? ”foo” : “bar”);

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)

>>> for n in range(2, 10): for (n=2; n<10; n++) {


... for x in range(2, n): ! good = true;
! for (x=2; x<n; x++)
... if n % x == 0:
! ! if (n % x == 0) {
... break ! ! ! good = false;
... else: !C/Java
! ! break;
... print n, ! ! } if (x==n)
... ! if (good)
! ! printf(“%d “, n);
}
prime numbers
25
Defining a Function def
• no type declarations needed! wow!
• Python will figure it out at run-time
• you get a run-time error for type violation
• well, Python does not have a compile-error at all

>>> def fact(n):


... if n == 0:
... return 1
... else:
... return n * fact(n-1)
...
>>> fact(4)
24
26
Fibonacci Revisited
>>> a, b = 0, 1
>>> while b <= 5:
... print b
... a, b = b, a+b
...
1
1 def fib(n):
2 ! if n <= 1:
3 ! ! return n
5 ! else:
! ! return fib (n-1) + fib (n-2)
conceptually cleaner, but much slower!
>>> fib(5)
5
>>> fib(6)
8
27
Default Values
>>> def add(a, L=[]):
... return L + [a]
...
>>> add(1)
[1]

>>> add(1,1)
error!

>>> add(add(1))
[[1]] lists are heterogenous!

>>> add(add(1), add(1))


???
[1, [1]]

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

dynamic Perl,VB Python, OCaml


29
Lists

heterogeneous variable-sized array


a = [1,'python', [2,'4']]
Basic List Operations
• length, subscript, and slicing
>>> a[0:3:2]
[1, [2, '4']]
>>> a = [1,'python', [2,'4']]
>>> len(a) >>> a[:-1]
3
[1, 'python']
>>> a[2][1]
'4' >>> a[0:3:]
>>> a[3]
[1, 'python', [2, '4']]
IndexError!
>>> a[-2] >>> a[0::2]
'python'
[1, [2, '4']]
>>> a[1:2]
['python'] >>> a[::]
[1, 'python', [2, '4']]

>>> a[:]
[1, 'python', [2, '4']]

31
+, extend, +=, append
• extend (+=) and append mutates the list!

>>> a = [1,'python', [2,'4']]


>>> a + [2]
[1, 'python', [2, '4'], 2]
>>> a.extend([2, 3])
>>> a
[1, 'python', [2, '4'], 2, 3]
same as a += [2, 3]

>>> 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]]

>>> [x, x**2 for x in vec]


SyntaxError: invalid syntax

>>> [(x, x**2) for x in vec]


[(2, 4), (4, 16), (6, 36)]

>>> vec1 = [2, 4, 6]


>>> vec2 = [4, 3, -9]
>>> [x*y for x in vec1 for y in vec2]
[8, 6, -18, 16, 12, -36, 24, 18, -54] (cross product)
>>> [x+y for x in vec1 for y in vec2]
[6, 5, -7, 8, 7, -5, 10, 9, -3]
should use zip instead!
>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
[8, 12, -54] (dot product) 35
Strings

sequence of characters
Basic String Operations
• join, split, strip

• upper(), lower()

>>> s = " this is a python course. \n"


>>> words = s.split()
>>> words
['this', 'is', 'a', 'python', 'course.']
>>> s.strip()
'this is a python course.'
>>> " ".join(words)
'this is a python course.'
>>> "; ".join(words).split("; ")
['this', 'is', 'a', 'python', 'course.']
>>> s.upper()
' THIS IS A PYTHON COURSE. \n'

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

>>> "this is a course".replace("is", "was")


'thwas was a course'
>>> "this is a course".replace(" is", " was")
'this was a course'
>>> "this is a course".replace("was", "were")
'this is a course'

these operations are much faster than regexps!


38
String Formatting
>>> print “%.2f%%” % 97.2363
97.24%

>>> s = '%s has %03d quote types.' % ("Python", 2)


>>> print s
Python has 002 quote types.

39

You might also like