Python 基本語法

Python 基本語法

  • main 主要描述程式的開始。就好比是 Java or C的 main
  • 註解用 # 開頭
  • 大小寫有區別
  • function 用 def 開頭
  • 每一行的空行是有特別意義的。因此,每段程式區塊的內縮必須一致!

 

[pastacode lang=”python” message=”Python main ” highlight=”” provider=”manual”]

# This is comments

def main():
   print ("This is main function called")
   b()

def b():
    print (This is b function called)

if __name__== "__main__":
    main()

[/pastacode]

if ..else..

要注意的是 python 每個判斷式後面都有加上 :

if …else…每段程式的空格是必須的

[pastacode lang=”python” message=”Python if else” highlight=”” provider=”manual”]

# If .. else ..

def main():
   a = 1
   b = 2

   if a < b:
        print("a  is less than b")
   elif a > b:
        print ("a is greater than b")
   else:
        print ("a is equal to b")

if __name__ == "__main__":
    main()

[/pastacode]

[pastacode lang=”python” message=”Python if else” highlight=”” provider=”manual”]

def main():
   a, b = 0, 1
   if a < b:
        print('a < b')
   else: 
        print('a > b')

if __name__ == "__main__": main()

[/pastacode]

function 定義

這個例子,主要定義一個 function ,印出 a-9的數字

[pastacode lang=”python” message=”Python function” highlight=”” provider=”manual”]

# This is comments

def main():
   func(1)
   func(6)

def func(a):
    for i in range(a, 10):
        print(i, end= ' ')
    print()

if __name__== "__main__":
    main()

[/pastacode]

Object

python的世界內,所有的變數、函數、程式都是物件。

變數也是物件! 是的。每個物件都會有一個 id。物件會有一定的生命周期。

  • imutable object: numbers, strings, tuples
  • mutable object: lists, dictionaries,

 

舉例來說,在 python Shell 下執行

>>>      x =  10

10

>>>   type(x)

<Class ‘int’>

>>>  id (x)

505401523

>>>  x = 40

        >>> id (x)

505409522

>>> x = 10

505401523

 

數字

[pastacode lang=”python” message=”Python number” highlight=”” provider=”manual”]

# This is comments
# the output will be
# <class 'int'> 1
# <class 'float'> 3.0

def main():
    num1 = 1 
    num2 = 3.0
    print(type(num1), num1)
    print(type(num2), num2)

if __name__== "__main__":
    main()

[/pastacode]

 

字串

python 有十分強大的字串處理功能,

[pastacode lang=”python” message=”Python string” highlight=”” provider=”manual”]

def  main():
   n = 10
   s = "this is {} string!".format(n)
   print(s)

if __name__ =="__main__": 
   main()

[/pastacode]

[pastacode lang=”python” message=”Python string” highlight=”” provider=”manual”]

# This is Python 2 syntax

def  main():
   n = 10
   s = "this is %s string!" %n
   print(s)

if __name__ =="__main__": 
   main()

[/pastacode]

 

變數 – list

 

[pastacode lang=”python” message=”Python variable list” highlight=”” provider=”manual”]

def main():
   x = 'string'
   print(type(x),x[2:5])
   print(type(x),x[3])
    
   a = [1,2,3] # It's a list. List is mutable. 
   a.append(5) # we can use append or insert to change the value.
   a.insert(0,7)
   print(type(a),a)
  
if __name__ == "__main__": main()

[/pastacode]

 

變數 – dictionary

python 獨特的變數, dictionary。

有些類似,可以自己建立自己的索引資料表。

例如,這個例子定義 one, two…five 每個元素的值

之後可以使用 sorted 的方式將 dictionary 定義的元素排序印出

[pastacode lang=”python” message=”Python dictionary” highlight=”” provider=”manual”]

def main():
   dic = dict(
       one = 1, two = 2, three = 3, four = 4, five = 'five'
   )

   for k in sorted(dic.keys()):
        print(k, dic[k])

if __name__ == "__main__": main()

[/pastacode]

迴圈

while

[pastacode lang=”python” message=”Python while” highlight=”” provider=”manual”]

# It's fibonacci 

def main():
   a, b = 0, 1
   while b < 10:
       print (b, end= ' ')
       a, b = b, a + b

if __name__ == "__main__": main()

[/pastacode]

利用for迴圈讀檔案

[pastacode lang=”python” message=”Python readfile” highlight=”” provider=”manual”]

def main():
    f = open('readfile.txt')
    for line in f.readlines():
        print(line)
if __name__ == "__main__": main()

[/pastacode]

搜尋一段字串

[pastacode lang=”python” message=”Python enumerate” highlight=”” provider=”manual”]

# search for the character t in the string
def main():
   s = 'this is a testing string for enumeration'
   for i, c in enumerate(s):
       if c == 't': print ('index {} is an t').format(i))

if __name__ == "__main__": main()

[/pastacode]

 

 

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *