1. 程式人生 > >【Python】Python簡單入門

【Python】Python簡單入門

Python介紹

  Python是一種高階的、動態型別的多範型程式語言。現在常用的Python版本是Python3.x。

Python程式碼通常被認為是虛擬碼,因為在簡明易懂的幾行程式碼中可以表達出非常強大的思想。

舉例說明,下面是Python中經典的快速排序演算法的實現:

>>> def quicksort(arr):
    if len(arr)<=1:
        return arr
    pivot = arr[len(arr)//2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quicksort(left) + middle + quicksort(right)

>>> print(quicksort([3,6,8,10,1,2,1]))
[1, 1, 2, 3, 6, 8, 10]

基本資料型別

  • python的基本資料有整型、浮點型、布林型別、strings型別,用法與其他程式語言相似。
  • python沒有自加自減的操作符,即python中不存在x++或是x–。
  • ‘/ ‘就表示浮點數除法,返回浮點結果,’ // ‘表示整數除法,**表示冪次方。
  • python的單行註釋是以 # 開頭,多行註釋是用三引號”’ ”’包含的。

數值計算

>>> x=3

>>> print(type(x))
<class 'int'>

>>> print(x)
3
>>> print(x+1)
4
>>> print(x-1)
2
>>> print(x*2)
6
>>> print(x**2)         # 2次方
9
>>> print(x**3)         # 3次方
27
>>> print(x/2)          # 浮點數除法
1.5
>>> print(x//2)         # 整數除法
1

>>> x+=1
>>> print(x)
4
>>> x*=2
>>> print(x)
8

>>> y = 2.5
>>> print(type(y))
<class 'float'>

>>> print(y,y+1,y*2,y**2)
2.5 3.5 5.0 6.25

布林型:

  python中有布林型別boolean,以英文表示而非字元如&&、||等。布林型別區分大小寫,正確寫法是True、False而非true、false。

>>> t = True
>>> f = False

>>> print(type(t))
<class 'bool'>

>>> print(t and f)      # 與 
False

>>> print(t or f)       # 或
True

>>> print(not t)        # 非
False

>>> print(t!=f)         
True

Strings:

>>> hello = 'hello'           # 入門第一步,hello world!
>>> world = "world"

>>> print(hello)
hello

>>> print(len(hello))
5

>>> hw = hello + ' ' + world
>>> print(hw)
hello world

>>> hw12 = '%s %s %d' % (hello,world,12)
>>> print(hw12)
hello world 12


>>> s = "hello"
>>> print(s.capitalize())     # 首字母大寫
Hello

>>> print(s.upper())          # 全部大寫
HELLO

>>> print("HELLO".lower())    # 全部小寫
hello

>>> print(s.rjust(7))         # 佔7位,右對齊
  hello

>>> print(s.ljust(7))         # 佔7位,左對齊
hello  

>>> print(s.center(7))        # 佔7位,中間對齊
 hello 

>>> print(s.replace('l','o')) # 替換
heooo

>>> print(' hello  world '.strip()) # 去除首尾空白符
hello  world

列表

Python含有幾個內建的容器型別:列表、字典、集合和元組。

列表List能包含多種不同型別的元素。在Python中相當於陣列,但它的大小可以改變。不同於元組的是,列表可動態增加,刪除,更新。

列表基本操作

>>> xs = [3,1,2]              # []定義列表

>>> print(xs,xs[2])           # 列表下標以0開始計數
[3, 1, 2] 2

>>> print(xs[-1])             # 負索引從列表的末尾開始計算
2
>>> print(xs[-2])
1

>>> xs[2] = 'foo'
>>> print(xs)
[3, 1, 'foo']

>>> xs.append('bar')          # 新增元素
>>> print(xs)
[3, 1, 'foo', 'bar']

>>> x = xs.pop()              # 刪除元素
>>> print(x,xs)
bar [3, 1, 'foo']

切片Slicing

>>> nums = list(range(5))

>>> print(nums)
[0, 1, 2, 3, 4]

>>> print(nums[2:4])          # 不含末位!
[2, 3]

>>> print(nums[2:])
[2, 3, 4]

>>> print(nums[:2])
[0, 1]

>>> print(nums[:])
[0, 1, 2, 3, 4]

>>> print(nums[:-1])          # 下表-1對應元素為4
[0, 1, 2, 3]

>>> nums[2:4] = [8,9]         # 替換
>>> print(nums)
[0, 1, 8, 9, 4]

列表迴圈

>>> animals = ['cat','dog','monkey']     
>>> for animal in animals:                    # 迴圈
    print(animal)

cat
dog
monkey

>>> for idx,animal in enumerate(animals):     # 列舉迴圈
    print('#%d: %s' % (idx + 1,animal))

#1: cat
#2: dog
#3: monkey

列表推導式List comprehensions

>>> nums = [0,1,2,3,4]              
>>> squares = []
>>> for x in nums:
    squares.append(x ** 2)  
>>> print(squares)
[0, 1, 4, 9, 16]


>>> nums = [0,1,2,3,4]
>>> squares = [x ** 2 for x in nums]
>>> print(squares)
[0, 1, 4, 9, 16]


>>> nums = [0,1,2,3,4]
>>> even_squares = [x ** 2 for x in nums if x % 2 == 0]
>>> print(even_squares)
[0, 4, 16]

字典

  字典是無序的,儲存鍵值對資料。最外面用大括號,每一組用冒號連起來,然後各組用逗號隔開。

字典基本操作

>>> d = {'cat':'cute','dog':'furry'}          # 定義字典

>>> print(d['cat'])                           # 輸出cat對應的值
cute

>>> print('cat' in d)                         # 判斷cat是否在字典裡
True

>>> d['fish'] = 'wet'                         # 為字典新增新元素
>>> print(d['fish'])
wet

>>> print(d['monkey'])                        # monkey不在字典內
KeyError: 'monkey'

>>> print(d.get('monkey','N/A'))              # 獲取失敗則輸出預設值'N/A'
N/A

>>> print(d.get('fish','N/A'))                # 獲取成功則輸出相應值
wet

>>> del d['fish']                             # 刪除元素
>>> print(d.get('fish','N/A'))
N/A

字典迴圈

>>> d = {'person':2,'cat':4,'spider':8}
>>> for animal in d:
    legs = d[animal]
    print('A %s has %d legs' % (animal,legs))

A person has 2 legs
A cat has 4 legs
A spider has 8 legs


# 獲取鍵值和相應值可以使用items方法
>>> d = {'person':2,'cat':4,'spider':8}
>>> for animal,legs in d.items():
    print('A %s has %d legs' % (animal,legs))

A person has 2 legs
A cat has 4 legs
A spider has 8 legs

字典推導式Dictionary comprehensions

>>> d = {'person':2,'cat':4,'spider':8}
>>> nums = [0,1,2,3,4]
>>> even_num_to_square = {x: x ** 2 for x in nums if x % 2 == 0}
>>> print(even_num_to_square)
{0: 0, 2: 4, 4: 16}

集合

  集合是一個無序不重複元素集。

集合基本操作

>>> animals = {'cat','dog'}                   # 定義集合           

>>> print('cat' in animals)                   # 判斷cat是否在集合內
True
>>> print('fish' in animals)                  # 判斷fish是否在集合內
False

>>> animals.add('fish')                       # 新增元素
>>> print('fish' in animals)
True
>>> print(len(animals))
3

>>> animals.add('cat')                        # cat在集合內,故不作改變
>>> print(len(animals))
3

>>> animals.remove('cat')                     # 刪除元素
>>> print(len(animals))
2

集合迴圈,由於無序,所以不能使用for…in…方法進行迴圈。

>>> animals = {'cat','dog','fish'}
>>> for idx,animal in enumerate(animals):
    print('#%d: %s' % (idx+1,animal))

#1: dog
#2: cat
#3: fish

集合推導式Set comprehensions

>>> from math import sqrt
>>> nums = {int(sqrt(x)) for x in range(30)}
>>> print(nums)
{0, 1, 2, 3, 4, 5}

元組
  元組是一個(不可變的)有序的值列表。元組在許多方面與列表相似,最重要的區別之一是,元組可以用作字典中的鍵,也可以作為集合的元素,而列表則不能。

  元組一旦定義其長度和內容都是固定的。一旦建立元組,則這個元組就不能被修改,即不能對元組進行更新、增加、刪除操作。

元組基本操作

>>> d = {(x,x+1): x for x in range(10)}       # 字典

>>> t = (5,6)                                 # 元組
>>> print(type(t))
<class 'tuple'>

>>> print(d[t])
5
>>> print(d[(1,2)])
1

函式

>>> def sign(x):
    if x > 0:
        return 'positive'
    elif x < 0:
        return 'negative'
    else:
        return 'zero'

>>> for x in [-1,0,1]:
    print(sign(x))

negative
zero
positive
>>> def hello(name,loud = False):
    if loud:
        print('HELLO, %s!' % name.upper())
    else:
        print('Hello, %s' % name)

>>> hello('Bob')
Hello, Bob

>>> hello('Fred',loud = True)
HELLO, FRED!

class Greeter(object):

    def __init__(self, name):
        self.name = name  # Create an instance variable

    def greet(self, loud=False):
        if loud:
            print('HELLO, %s!' % self.name.upper())
        else:
            print('Hello, %s' % self.name)

g = Greeter('Fred')  
g.greet()            
g.greet(loud=True)   

# 執行結果:
# Hello, Fred
# HELLO, FRED!