Python 3.4

安裝Python 3.4

% cd /usr/ports/lang/python3
% make install clean

什麼是Python

  • Python是open source
  • 在1990年由Guido van Rossum開發.
  • 有Python 2 和 Python 3 版本

如何執行Python3

撰寫範例程式

% nano test.py

tesyt.py

name = 'wssu'                   # 變數宣告
def say_hello( where ):         # 此行為定義函式
    print('hello',name + '@'+ where +'!')
    print("hello {name} @ {where}!".format(name=name ,where=where))
say_hello('ph302')

執行程式

% python3.4 test.py

變數

  • 不用定義型別
  • 句尾不用分號
  • 可以改變型別 (弱型別 Weak Type)
    n = 0
    f= 9.99
    str = '一大堆字的字串'
    fruit = 'apple'
    print ( str )
    print ( fruit )
    

    Output: 一大堆字的字串 apple

註解

  • 單行註解

    #print ('我被註解了~')
    print ('我沒被註解!')
    # print ('我又被註解了!!')
    print ('哈哈哈哈')
    

    output: 我沒被註解! 哈哈哈哈

  • 多行註解:用 ''' 包住想要註解的內容

    n = 9
    m = 10
    ''' print( '從這行開始" )
    n = 0
    m = 1
    print( '一直註解到這邊' )  '''
    print ( n, m )
    

    output: 9 10

流程控制

if-else

if <條件1 > :
    #敘述1
elif < 條件2 > :
    #敘述2
else :
    #敘述ˇ

while

while <條件>:
    #敘述1

for

for i in range( 10 ):
    print (i, end=' ')      # end='' 為不換行

Output: 0 1 2 3 4 5 6 7 8 9

for i in range( 0, 20, 2 ):
    print (i, end=' ')

Output: 0 2 4 6 8 10 12 14 16 18

fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
    print ('fruit '+fruit)
print(len(fruits))

Output: fruit apple fruit banana fruit orange 3

for c in 'hello':
    print (c)
for fruit in ['apple', 'banana', 'watermelon']:
    print (fruit)

Output: h e l l o apple banana watermelon

邏輯條件

True, False
not, and, or
is, in
== , != , > , <

is

'abc' is  'qoo'             # Output: False

is not

'banana' is not 'apple'     # Output: True

in

'a' in 'apple'              # Output: True

字串處理

str = "Hello, I'm a String"
print(len(str))             # 輸出字串長度:19
print(str[3])               # 輸出第3個字元:l
print(str[5:12])            # 輸出第5~12位置的子字串:", I'm a"
print(str[-3])              # 輸出倒數第3個字元:i
print(str[-3:-1])           # 輸出倒數第3個字元到倒數第1個字元:in
print(str[13:])             # 輸出str[12]到最後:String
print(str[:8])              # 輸出最前面到str[8]的位置:Hello, I
print(str[::-1])            # 字串倒轉輸出:gnirtS a m'I ,olleH
text = '<pwd>i_am_password</pwd>'
start = text.find('<pwd>')
end = text.find('</pwd>')
print (start)
print (end)
print (text[ start+5: end])

Output: 0 18 i_am_password

List

c = [1,2,3,4,5,6,7,8,9,10,'嗨嗨','好久不見']
c + ['早安', '午安', '晚安']        # list後面加上三個元素
c.sort()                            # 排序
c.pop()                             # 移除最後一個元素
c.append('abc')                     # 在最後面新增abc元素
  • 建立平方串列
    squares = []
    for x in range(10):
      squares.append(x**2)
    print (squares)
    # Output:[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    

Dictionary

d = {"name":"wssu", "age": 20 ,"job": "student"}
for i in d:
    print (i)
    print (d[i])

Tuple

a=['早安','你好']
b=['晚安','再見']
(a,b) =(b,a)                #交換a與b串列
print(a,b)                  #Output:['晚安', '再見'] ['早安', '你好']
def f(x):
    a= 2 * x
    b= 3 * x
    c= 4 * x
    return a, b, c
x, y, z =f(10)
print(x, y, z)              #Output:20 30 40

輸入

hello = {"apple":"200","orange":"99"}       # 建立dictionary結構
while True:
    word = input("Input:")                  # 輸入字串,並存到word變數中
    if not word:
        break                               # 若沒有輸入,則跳離開迴圈
    else:
        print(hello.get(word),"1234")       # 取得輸入變數,對應到dictionary的值

Output: 輸入字串apple 200 1234 輸入字串orange 99 1234 輸入字串abc None 1234 輸入字串

def f(x):                           # 定義f函式,可傳入x參數
    print(2+int(x))                 # 指定x為int格式

f(input("Tpye a number:"))

Output: Tpye a number:9 11

輸入的例外處理

def f(x):
    try:                            # 判斷以下程式碼是否有可能發生例外
        print(2+float(x))
    except ValueError:
            print("error!Please tpye a number")     # 若發生ValueError例外

f(input("Tpye a number:"))

Output: Tpye a number:abc error!Please tpye a number

words = {}
words["apple"]="n. An evil company"
while True:
    word =input("輸入詞彙: ")
    if not word:
        break
    else:
        print(words[word])

results matching ""

    No results matching ""