Skip to content

johnnyGogo/pythonTutor

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

tutor code

  1. Base
    1. Syntax
    2. Variables
      1. get variable type
      2. convert type
      3. enum
      4. 作用域
    3. Operators
      1. 三元運算
      2. if
      3. else if
      4. else
      5. ==
      6. True / False
      7. while ... else
      8. break / continue
      9. for ... else
      10. range()
      11. switch / case
    4. Number
    5. Strings
      1. 常數
      2. 切片
      3. 長度
      4. 分割
      5. 連結
      6. 取代
      7. 尋找或計算
      8. 格式化
      9. 判斷
      10. Regular Expressions
    6. Iterate
      1. List
      2. Set
      3. Dict
    7. Iterate Advanced
      1. filter
      2. map
      3. reduce
    8. Lambda
    9. Functions
    10. Closure
    11. Modules
    12. Classes and Objects
      1. 類別方法
    13. DateTime
      1. 時區
      2. 時間加減
      3. 格式化
    14. JSON
    15. System
    16. Try...Except
    17. 網路
      1. 解析url
  2. 演算法 Algorithm
    1. 亂數
  3. 功能 / Framework
    1. CSV

Base

Syntax

每行不用; , 使用縮進2格或4格

Comments: # Docstrings: """ or '''

keywords: https://www.programiz.com/python-programming/keyword-list

Variables

內建資料類型:

  • boolean : True / False
  • int : e.g. 42, 100000
  • float : e.g. 3.14159, 1.0e8
  • string : 'abc'
  • enum

get variable type

type()

convert type

int({str})

enum

作用域

LEGB


Operators

三元運算

condition_is_true if condition else condition_is_false

if

if condition:
	pass

else if

if condition:
	pass
elif condition:

else

if condition:
	pass
else:
	pass

==

True / False

True True, 'abc', 1, -1, [1,2]

False False, None, 0, 0.0, '', [], (), {}, set()

while ... else

break / continue

for ... else

range()

switch / case

python 沒有 替代方式 dictionary

def numbers_to_strings(argument):
    switcher = {
        0: "zero",
        1: "one",
        2: "two",
    }
    return switcher.get(argument, "nothing")

Number


Strings

常數

  • string.ascii_letters
  • string.ascii_lowercase
  • string.ascii_uppercase
  • string.digits
  • string.hexdigits
  • string.octdigits

切片

str[start : end : step]

長度

len(str)

分割

string to array str.split(str="", num=string.count(str)) str.rsplit(str="", num=string.count(str))

str = "Line1-abcdef \nLine2-abc \nLine4-abcd";
print str.split( );
print str.split(' ', 1 );

連結

','.join()

取代

  • replace: str.replace(old, new[, max]) default max可指定替換次數
  • strip: 預設去除空白 ' abcabc '.strip()

尋找或計算

  • find: 找不到則為-1 str.find(find_str)
  • rfind: str.rfind(find_str)
  • count: str.count(count_str)

格式化

判斷

  • startswith: 字首是不是 str.startswith({word})
  • endswith: 字尾是不是 str.endswith({word})
  • isalnum: 是否只有英數 str.isalnum()

Regular Expressions

tools: https://regex101.com/ tutorial: http:https://zwindr.blogspot.com/2016/01/python-regular-expression.html

import re

phone = "123-456-7890"
search = re.search(r'(\d{3})-(\d{3})-(\d{4})', phone)
if search is not None:
    pass
search.group(1)..


# re
re.compile(pattern, flags=0) 
re.search(pattern, string, flags=0)
re.match(pattern, string, flags=0)
re.split(pattern, string, maxsplit=0, flags=0)
re.sub(pattern, repl, string, count=0, flags=0)

# match
match.group([group1, ...])

pattern = re.compile(r'(\w*) (\w*)(?P<tt>.*)')
match = pattern.match('hello world!!!')
print(match.group(0))
# >> !!!
print(match.group(3))
#同上 >> !!!
print(match.group('tt'))

Iterate

List

Set

Dict


Iterate Advanced

filter

f = filter(fn, array)

map

m = map(fn, array)

reduce

d = reduce(fn, array)

Lambda

f = lambda arg1, arg2, ....: expression

Functions


Closure


Modules


Classes and Objects

類別方法

class Some:
    def __init__(self, x):
        self.x = x

    @classmethod
    def service(clz, y):
        print('do service...', clz, y)

Some.service(30)

DateTime

import datetime
import time

# datetime
now = datetime.datetime.now()
now = datetime.datetime.utcnow()

# timestamp
time.time()

# time tuple
time.localtime()

# date
now.date()

時區

import pytz

now = datetime.datetime.utcnow()

# 從國家取得時區
pytz.country_timezones(‘cn’)

# 取得時區時間
tz = pytz.timezone('Asia/Tokyo')
datetime.datetime.now(tz)

時間加減

datetime.timedelta

datetime.datetime.now() - datetime.timedelta(days=3)

# 時間差
(datetime.datetime(2015,1,13,12,0,0) - datetime.datetime.now()).total_seconds()

格式化

time.strftime("%Y-%m-%d %H:%M:%S")

datetime.datetime.strptime("2014-12-31 18:20:10", "%Y-%m-%d %H:%M:%S")


JSON

  • json.dumps: dict to json
  • json.loads: json to dict

System


Try...Except


網路

解析url

urlparse

from urllib.parse import urlparse
o = urlparse('http:https://www.cwi.nl:80/%7Eguido/Python.html')

o.scheme
o.geturl()

演算法 Algorithm


亂數

import random

random.randint(0,99)            # 隨機整數
random.randrange(0, 101, 2)     # 隨機選取0到100間的偶數
random.choice('abcdefg&#%^*f')  # 隨機字元
random.sample(range(20), 20)
random.sample('abcdefghij',3)   # 多個字元中選取特定數量的字元
random.shuffle([1, 2, 3, 4, 5, 6])  # 洗牌

功能 / Framework


CSV

https://docs.python.org/3/library/csv.html https://blog.gtwang.org/programming/python-csv-file-reading-and-writing-tutorial/

About

python tutor

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages