Try   HackMD

Introduction to Python

Table of Content

Introduction

  • Python is free and easy to learn
  • 超多 standard libary, community
  • 支援領域廣(machine learning, data science, web servers, DB…)
  • 語法簡潔、易寫易讀

Python 語法特徵

  • 直譯式語言,開發、除錯速度快
  • 使用縮排(indention)分隔程式段落
  • 多種基本的資料型別: numbers, strings, lists and dictionaries
  • 支援 OOP 用法(classes and multiple inheritances)
  • 進階用法: generators, list comprehensions

Input/Output

>>> name = input('What is your name?\n') vayne # 使用者輸入 >>> print ('Hi, %s.' % name) Hi, vayne.

Variable

Types

a = 123 # int b = 1.23 # float c = 1.2 + 2.3j # complex d = (True or False) # boolean e = [1, 2, 3] # list f = (1, 2, 3) # tuple g = {'a': 1, 'b': 2} # dictionary h = 'abc' # string l = None # None

Number

>>> x = 5 # int >>> y = 1.9 # float >>> print(x + y) 6.9 >>> x = 10 # 修改變數值 >>> print(x + y) 11.9
>>> 3 / 2 # true division: 1.5 >>> 3 // 2 # division: 1 >>> 3 % 2 # mod: 1 >>> 3 ** 2 # power: 9 >>> float(3) # 3.0 (float) >>> int(1.5) # 1(int) >>> round(1.5) # 2 (int)

List (mutable)

heros = ['Zed', 'Ezreal'] # heros: ['Zed', 'Ezreal'] heros[1] = 'Vayne' # heros: ['Zed', 'Vayne'] heros.append('Yasuo') # heros: ['Zed', 'Vayne', 'Yasuo'] heros.extend(['jinx, Twitch']) # heros: ['Zed', 'Vayne', 'Yasuo', 'Jinx', 'Twitch']

Tuple (immutable)

heros = ('Zed', 'Ezreal') # heros: ('Zed', 'Ezreal') heros = 'Zed', 'Ezreal' # heros: ('Zed', 'Ezreal') heros[1] = 'Vayne' # error mid, adc = heros # mid: 'Zed' # adc: 'Ezreal'

Indexing and Slicing

  • Usage: [ start: end (不含) : step (default 1) ]
a = [0, 1, 2, 3, 4] len(a) # 5 a[0] + a[-1] # 0 + 4 = 4 a[2:-1] # [2, 3] a[0:5:2] # [0, 2, 4] a[::-1] # [4, 3, 2, 1, 0]

Dict (mutable)

  • Usage: {key: value}
d = dict({'a': 1, 'b': [1, 2]}) # d: {'a': 1, 'b': [1, 2]} d['a'] = '3' # d: {'a': 3, 'b': [1, 2]} d.items() # [('a', 3), ('b', [1, 2])] d.keys() # ['a', 'b'] d.values() # [3, [1, 2]]

Str (immutable)

  • Usage: 單引號、雙引號、三引號
a = '單引號' b = "雙引號" c = ''' 三引號 多行 ''' d = len('a b c') # 5 e = 'a b c'.split() # ['a', 'b', 'c'] f = a + ' ' + b # '單引號 雙引號' a[0] = 'e' # error

Control Flow

If, elif, else

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b
a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b")

For, While

Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) # apple # banana # cherry

Loop through the letters in the word “banana”:

for x in "banana": print(x) # b # a # n # a # n # a

The range() Function

for x in range(6): print(x) # 0 # 1 # 2 # 3 # 4 # 5

Print i as long as i is less than 6:

i = 1 while i < 6: print(i) i += 1 # 1 # 2 # 3 # 4 # 5

The break Statement

i = 1 while i < 6: print(i) if i == 3: break i += 1 # 1 # 2 # 3

The continue Statement

Continue to the next iteration if i is 3:

i = 0 while i < 6: i += 1 if i == 3: continue print(i) # 1 # 2 # 4 # 5 # 6

Function

Creating a Function

def my_function(): print("Hello from a function")

Calling a Function

def my_function(): print("Hello from a function") my_function()

Arguments

def my_function(name): print("Hi " + name) my_function("David") # Hi David

Number of Arguments

This function expects 2 arguments, and gets 2 arguments:

def my_function(fname, lname): print(fname + " " + lname) my_function("David", "Jiang") # David Jiang

This function expects 2 arguments, but gets only 1:

def my_function(fname, lname): print(fname + " " + lname) my_function("Weieie") # error

Arbitrary Arguments, *args

If the number of arguments is unknown, add a * before the parameter name:

def my_function(*kids): print("The youngest child is " + kids[2]) my_function("Emil", "Tobias", "Linus") # The youngest child is Linus

Keyword Arguments

You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

def my_function(child3, child2, child1): print("The youngest child is " + child3) my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")

Arbitrary Keyword Arguments, **kwargs

If the number of keyword arguments is unknown, add a double ** before the parameter name:

def my_function(**kid): print("His last name is " + kid["lname"]) my_function(fname = "Tobias", lname = "Refsnes")

Classes

Create a Class

Create a class named MyClass, with a property named x:

class MyClass: x = 5

Create Object

Now we can use the class named MyClass to create objects:

p1 = MyClass() print(p1.x) # 5

The __init__() Function

The __init __() function is called automatically every time the class is being used to create a new object.

class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) # John print(p1.age) # 36

class的概念是屬性集合,而不是所有物

Object Methods

class Person: def __init__(self, name, age): self.name = name self.age = age def myfunc(self): print("Hello my name is " + self.name) p1 = Person("John", 36) p1.myfunc()

Modules

import … as …

使⽤該 package 的函式、物件要前綴 package 的名稱。

import math import numpy as np np.zeros((5, 1)) math.floor(1.5) math.ceil(1.3)

from … import … as …

將該 package 底下的函式、物件加⼊當前 namespace 中。

from math import floor, ceil from numpy import zeros as zs zs((5, 1)) floor(1.5) ceil(1.3)
tags: python guide