In [4]:
print type(1.5)
print type(1+2j)
In [ ]:
http://composingprograms.com/pages/21-introduction.html
從2.2課文開始,我們要探討的是data abstraction, 抽象化(abstraction)是一個重要的技巧,我也不太懂重要在哪裡,讓我們看看大神如何用有理數的例子帶我們一窺門路吧!
In [4]:
print type(1.5)
print type(1+2j)
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]:
或是我們可用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]:
In [12]:
def cheer():
#但我們沒拿range裡面東西辦事的時候用_, 我們bucare, 以表示清白XD
for _ in range(3):
print("Go Michael = =!")
cheer()
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]:
In [15]:
{'I':1, 'V':5, 'X':10}
Out[15]:
In [ ]: