In [4]:
print type(1.5)
print type(1+2j)


<type 'float'>
<type 'complex'>

In [ ]:
http://composingprograms.com/pages/21-introduction.html

2.2課文開始,我們要探討的是data abstraction, 抽象化(abstraction)是一個重要的技巧,我也不太懂重要在哪裡,讓我們看看大神如何用有理數的例子帶我們一窺門路吧!


In [4]:
print type(1.5)
print type(1+2j)


<type 'float'>
<type 'complex'>

2.3 Sequences

Sequence是最基礎的data type,

for是設計用來處理sequence的statement之一


In [8]:
def count(s, value):
    """count the value of times that value occurs
    
    >>> count([1,2,3,4,32,21,1],1)
    2
    
    """
    total, index = 0,0
    while index < len(s):
        element = s[index]
        if element == value:
            total+=1
        index += 1
    return total

In [9]:
#with for, we can do this!
#這個技巧叫做sequence unpacking
def count(s, value):
    """count the value of times that value occurs
    
    >>> count([1,2,3,4,32,21,1],1)
    2
    
    """
    total=0
    for element in s:
        if element == value:
            total+=1
    return total
count([1,2,3,4,32,21,1],1)


Out[9]:
2

或是我們可用range, range is a "range", not a list Ranges. A range is another built-in type of sequence in Python, which represents a range of integers. Ranges are created with range, which takes two integer arguments: the first number and one beyond the last number in the desired range.


In [13]:
list(range(2,7))

def sum_below(n):
    total = 0
    for i in range(n):
        total +=i
    return total
sum_below(10)


Out[13]:
45

In [12]:
def cheer():
    #但我們沒拿range裡面東西辦事的時候用_, 我們bucare, 以表示清白XD
    for _ in range(3):
        print("Go Michael = =!")
cheer()


Go Michael = =!
Go Michael = =!
Go Michael = =!

List Comprehensions. Many sequence processing operations can be expressed by evaluating a fixed expression for each element in a sequence and collecting the resulting values in a result sequence. In Python, a list comprehension is an expression that performs such a computation.


In [14]:
odds = [1,3,5,7,9]
[x+1 for x in odds]


Out[14]:
[2, 4, 6, 8, 10]

Strings

  1. strings are sequence! len, element selection 可用!
  2. +, * 也OK
  3. in 也合用(回傳部份string 是否存在於另一段string中) “”“ 可以用來存長長的string 分行也OK\n注意C style的backslash n for newline is also working here! ”“”
  • 另外str() 是string 的constructor 裡面可以放numeral, lists, 主要會跑出人看得懂的string

Dictoinaries

Dictonary 沒有順序,


In [15]:
{'I':1, 'V':5, 'X':10}


Out[15]:
{'I': 1, 'V': 5, 'X': 10}