流程控制


In [129]:
## 比較函示
'''
Equal to (==)
Not equal to (!=)
Less than (<)
Less than or equal to (<=)
Greater than (>)
Greater than or equal to (>=)
'''
##比較函示會吐出True or False

a =  5 > 4
print a

b = 5 == 4
print b


True
False

In [130]:
## and 兩者皆真為真
## or 兩者有一真為真
## not 否定
#真值表


a = True and True
b = True and False
c = False and False
d = True or True
e = True or False
f = False or False
g = not False

print a, b, c, d, e, f, g


True False False True True False True

In [131]:
# if, elif and else

a = -1


if a > 3:
    print "a > 3"
elif a == 3:
    print "a = 3"
else:
    print "a < 3"


a < 3

物件與方法


In [132]:
#Python 是物件導向語言
#每個東西都是物件,不同的物件之中有不同的方法來操作

class car:
    wheel = 4
    max_speed = 90
    
    #建立物件時自動呼叫的方法,參數預設要加入"self"
    def __init__(self):
        print "Let's Go!"
    
    def get_wheel(self):
        print "wheel = ", self.wheel
    
    def set_max_speed(self,speed):
        if speed > self.max_speed:
            print "Too Fast!"
        elif (speed <= self.max_speed) & (speed > 0):
            print "Safe!"
        else:
            print "Stop"
        

#我們不能直接操作物件,要操作物件之前,必須將物件實體化
car = car()
car.get_wheel()
car.set_max_speed(0)


Let's Go!
wheel =  4
Stop

In [133]:
##建立方法

def test():
    print "It's my first function in Python!"
    
test()


It's my first function in Python!

In [134]:
## 加入參數

def tax(income):
    tax = 1.035
    return income * tax


tax(50000)
# str(tax(50000))

#有關浮點數運算的誤差可以參考這篇:
#http://www.codedata.com.tw/python/python-tutorial-the-2nd-class-1-numeric-types-and-string/


Out[134]:
51749.99999999999

In [135]:
#PYTHON在設定參數的時候,不用指定參數型態

def super_print(x):
    print x

super_print("cool")
super_print(13+5)
super_print([1,2,3,4,5])


cool
18
[1, 2, 3, 4, 5]

In [136]:
def super_print(x):
    for i in x:
        print i

super_print("cool")
#super_print(13+5)
super_print([1,2,3,4,5])


c
o
o
l
1
2
3
4
5

獨特的資料型態:List和Dictionary


In [137]:
#list 就是 array
zoo_animals = ["pangolin", "cassowary", "sloth", "cool"];


if len(zoo_animals) > 3:
	print "The first animal at the zoo is the " + zoo_animals[0]
	print "The second animal at the zoo is the " + zoo_animals[1]
	print "The third animal at the zoo is the " + zoo_animals[2]
	print "The fourth animal at the zoo is the " + zoo_animals[3]


The first animal at the zoo is the pangolin
The second animal at the zoo is the cassowary
The third animal at the zoo is the sloth
The fourth animal at the zoo is the cool

In [138]:
numbers = [1,2,3,4]
print "數列長度: ",len(numbers)

print numbers[0]
print numbers[1]
print numbers[2]
print numbers[3] + numbers[1]


數列長度:  4
1
2
3
6

In [139]:
## change the content of a list
numbers[3] = 5
print numbers

numbers.append(10)
print "append : ", numbers

numbers.insert(2,100)
print "insert : ",numbers

##只能移除第一個碰到的元素
numbers.remove(100)
print "remove : ",numbers

numbers.sort()
print "sort : ",numbers


[1, 2, 3, 5]
append :  [1, 2, 3, 5, 10]
insert :  [1, 2, 100, 3, 5, 10]
remove :  [1, 2, 3, 5, 10]
sort :  [1, 2, 3, 5, 10]

In [140]:
## cut the lis
numbers_a = numbers[1:4]
print numbers_a

numbers_b = numbers[:4]
print numbers_b

numbers_c = numbers[1::2]
print numbers_c


[2, 3, 5]
[1, 2, 3, 5]
[2, 5]

In [141]:
## 三倍長度
print 3 * numbers

## 分別操作list中的每個元素
for i in numbers:
    print i 
    
for i in numbers:
    print i * 3


[1, 2, 3, 5, 10, 1, 2, 3, 5, 10, 1, 2, 3, 5, 10]
1
2
3
5
10
3
6
9
15
30

In [142]:
# Dictionary 就是key and value

residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}

print residents['Puffin'] # Prints Puffin's room number
print residents["Sloth"]
print residents["Burmese Python"]


104
105
106

In [143]:
#建立新的key
residents['Bryan']=107
print "create a new key: ", residents

#改變value
residents['Bryan']=207
print "change a key: ",residents['Bryan']

#移除key

del residents["Bryan"]
print "remove a key: ",residents


create a new key:  {'Sloth': 105, 'Puffin': 104, 'Burmese Python': 106, 'Bryan': 107}
change a key:  207
remove a key:  {'Sloth': 105, 'Puffin': 104, 'Burmese Python': 106}

In [144]:
# 用for迴圈操作list

for i in residents:
    print i, residents[i]


Sloth 105
Puffin 104
Burmese Python 106

In [145]:
def room(name):
    for n in residents:
        if n == name:
            print name, "is living in room",residents[n]
            ##若已經找到對象,則跳脫迴圈
            break
    ##如果for迴圈結束後沒有結果,則跳到else
    else:
        print "There is no this man"

room("Puffin")


Puffin is living in room 104

In [146]:
#Dictionary 內部的value可以放的東西
inventory = {
    'gold' : 500,
    'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
    'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']
}


# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 

# Your code here
inventory["pocket"] = ["seashell","strange berry", "lint"]
inventory["backpack"].sort()
inventory["backpack"].remove("dagger")
inventory["gold"]+=50

print inventory


{'pocket': ['seashell', 'strange berry', 'lint'], 'backpack': ['bedroll', 'bread loaf', 'xylophone'], 'pouch': ['flint', 'gemstone', 'twine'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 550}