# Happy Python Day https://github.com/MyFirstSecurity2020/HappyPythonDay https://hackmd.io/@ss8651twtw/python ss8651twtw --- ## 環境資訊 - Ubuntu 18.04 - Python 3.8 - [回家練習環境](https://drive.google.com/file/d/1mDmjexzPsFuI8p7EzY0Uy1xZ0-Fj-vkj/view?usp=sharing) --- ## 安裝 Python 輕鬆容易 立即上手 ---- ### 官網下載安裝 https://www.python.org/downloads/ ---- ### 指令下載安裝 ```shell sudo apt install python3 ``` ---- ### pyenv 管理不同版本的 Python 方便切換使用 https://github.com/pyenv/pyenv --- ## 使用 Python ---- ### Python 直譯器 ```shell $ python3 Python 3.8.3 (default, Jul 8 2020, 14:27:55) [Clang 11.0.3 (clang-1103.0.32.62)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ``` ---- ### Python 腳本 將程式寫成一個檔案 再使用 `python3` 執行 ```shell python3 script.py ``` --- ## Hello, World! ```python print("Hello, World!") ``` ---- ### 語法簡單 ```python x = 1 if x == 1: # indented four spaces print("x is 1.") ``` ---- ![](https://i.imgur.com/Gyzp1ua.png) ---- ### 縮排 (indent) - 支援 tab 或空格但不可混用 - 官方標準為 4 個空格縮排 ---- ![](https://i.imgur.com/zhyviBc.png) --- ## 變數與型態 物件導向 動態型別 ---- ### 變數命名 不能是關鍵字、不能是數字開頭、不能包含運算子 ```python ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] ``` ---- ### 指派運算子 ```python a, b = 3, 4 print(a,b) a, b = "haha", "lala" print(a,b) ``` ---- ![](https://i.imgur.com/llGlzhf.png) ---- ### 數字 整數 (int)、浮點數 (float) ```python myint = 7 print(myint) myfloat = 7.0 print(myfloat) myfloat = float(7) print(myfloat) ``` ---- ### 整數相關函式 ```python bin(5) oct(9) hex(32) int('10') int('10', 16) ``` ---- ### 字串 (string) 顯示出來的圖案 ```python mystring = 'hello' print(mystring) mystring = "hello" print(mystring) ``` ---- ### 字串相關函式 ```python str(5566) chr(0x61) ord('a') len('haha') ``` ---- ### 位元組 (bytes) 實際儲存的數值 ```python mybytes = b'hello' print(mybytes) print(mybytes.hex()) print(bytes.fromhex('68616861')) ``` ---- ### 字串與位元組轉換 ```python astring = "哈哈" print(astring) abytes = astring.encode("utf8") print(abytes) astring = abytes.decode("utf8") print(astring) ``` ---- ### 列表 (list) ```python mylist = [] mylist.append(1) mylist.append(2.8) mylist.append("haha") print(mylist[0]) # prints 1 print(mylist[1]) # prints 2.8 print(mylist[2]) # prints haha # prints out 1, 2.8, haha for x in mylist: print(x) ``` ---- ### 字典 (dict) 鍵 (key) 值 (value) ```python phonebook = {} phonebook["John"] = 938477566 phonebook["Jack"] = 938377264 print(phonebook) phonebook = {"John" : 938477566,"Jack" : 938377264} for name, number in phonebook.items(): print(f"Phone number of {name} is {number}") ``` ---- ### 集合 (set) ```python a = set(["Jake", "John", "Eric"]) b = set(["John", "Jill"]) print(a.intersection(b)) print(a.union(b)) print(a.difference(b)) print(a.symmetric_difference(b)) ``` --- ## 基本運算子 運算操作 方便直覺 ---- ### 算術運算子 - 加 \+ - 減 \- - 乘 \* - 除 \/ (浮點數除法) - 除 \// (整數除法) - 取餘數 \% - 冪次 \** ---- ```python number = 1 + 2 * 3 / 4.0 print(number) remainder = 11 % 3 print(remainder) squared = 7 ** 2 cubed = 2 ** 3 print(squared) print(cubed) ``` ---- ![](https://i.imgur.com/enyiVg7.png) ---- ### 比較運算子 - 大於 \> - 小於 \< - 等於 \== - 大於等於 \>= - 小於等於 \<= - 不等於 \!= ---- ### 比較數字大小 ```python a = 5 # type(a) -> int b = 3.14 # type(b) -> float a > b ``` ---- ![](https://i.imgur.com/8Q4nTic.png) ---- ### 邏輯運算子 - 且 and - 或 or - 異或 \^ - 非 not ---- | A | B | A and B | A or B | A ^ B | not A | |:-----:|:-----:|:-------:|:------:|:-----:|:-----:| | True | True | True | True | False | False | | True | False | False | True | True | False | | False | True | False | True | True | True | | False | False | False | False | False | True | ---- ### 字串運算子 - 加 \+ - 乘 \* ---- ```python helloworld = "hello" + " " + "world" print(helloworld) lotsofhellos = "hello" * 10 print(lotsofhellos) ``` ---- ### 列表運算子 - 加 \+ - 乘 \* ---- ```python even_numbers = [2,4,6,8] odd_numbers = [1,3,5,7] all_numbers = odd_numbers + even_numbers print(all_numbers) print([1,2,3] * 3) ``` --- ## 基本字串操作 字串處理 各種姿勢 ---- ### 字串長度 ```python astring = "Hello world!" print(len(astring)) ``` ---- ### 字串位置 ```python astring = "Hello world!" print(astring.index("o")) ``` ---- ### 字串計數 ```python astring = "Hello world!" print(astring.count("l")) ``` ---- ### 子字串 \[start:stop:step\] ```python astring = "Hello world!" print(astring[3:7]) print(astring[3:7:2]) print(astring[::-1]) ``` ---- ### 字串大小寫轉換 ```python astring = "Hello world!" print(astring.upper()) print(astring.lower()) ``` ---- ### 字串前後綴判斷 ```python astring = "Hello world!" print(astring.startswith("Hello")) print(astring.endswith("asdfasdfasdf")) ``` ---- ### 格式化字串 ```python print('{}, {:.1f}'.format('haha', 7.777)) ``` ---- ### 字串切割 ```python astring = "Hello world!" afewwords = astring.split(" ") ``` --- ## 條件判斷 是真是假 各自表述 ---- ### 條件語句 ```python x = 2 print(x == 2) # prints out True print(x == 3) # prints out False print(x < 3) # prints out True statement = False another_statement = True if statement is True: # do something pass elif another_statement is True: # else if # do something else pass else: # do another thing pass ``` ---- ### 比較與邏輯運算子 ```python name = "John" age = 23 if name == "John" and age == 23: print("Your name is John, and you are also 23 years old.") if name == "John" or name == "Rick": print("Your name is either John or Rick.") print(not False) # Prints out True print((not False) == (False)) # Prints out False ``` ---- ### in 運算子 ```python name = "John" if name in ["John", "Rick"]: print("Your name is either John or Rick.") ``` ---- ### is 運算子 判斷是否為相同實例 (instance) ```python x = [1,2,3] # check id(x) y = [1,2,3] # check id(y) print(x == y) # Prints out True print(x is y) # Prints out False ``` --- ## 迴圈 相同內容 重複執行 ---- ### for 迴圈 ```python primes = [2, 3, 5, 7] for prime in primes: print(prime) for x in range(5): print(x) for x in range(3, 6): print(x) for x in range(3, 8, 2): print(x) ``` ---- ### while 迴圈 ```python # Prints out 0,1,2,3,4 count = 0 while count < 5: print(count) count += 1 # This is the same as count = count + 1 ``` ---- ### break 及 continue 語句 ```python # Prints out 0,1,2,3,4 count = 0 while True: print(count) count += 1 if count >= 5: break # Prints out only odd numbers - 1,3,5,7,9 for x in range(10): # Check if x is even if x % 2 == 0: continue print(x) ``` ---- ![](https://i.imgur.com/tJc7V5R.png) ---- ![](https://i.imgur.com/aqNoKIm.png) --- ## 函式 拆分邏輯 好讀易用 ---- ### 函式定義 ```python def my_function(): print("Hello From My Function!") def sum_two_numbers(a, b): return a + b ``` ---- ### 函式使用 ```python # print(a simple greeting) my_function() # after this line x will hold the value 3 x = sum_two_numbers(1,2) ``` --- ## 模組與套件 ~~製造輪子 造福大眾~~ ---- ### 套件安裝 ```shell pip3 install <package name> ``` ---- ### 套件使用 ```python import <package name> from <package name> import <function name> from <package name> import <variable name> from <package name> import <class name> ``` ---- ```python import random print(random.randint(0, 100)) ``` ---- ```shell pip3 install pwntools ``` ---- ```python from pwn import * ip = "127.0.0.1" port = 10000 r = remote(ip, port) res = r.recv() print(res) r.interactive() ``` --- ## 異常處理 ```python try: print(好想下課) except: print("error") ``` --- ## 延伸學習 - 列表生成 (list comprehensions) - [Map, Filter, Reduce](https://www.learnpython.org/en/Map%2C_Filter%2C_Reduce) - [類別與物件 (class and object)](https://www.learnpython.org/en/Classes_and_Objects) - [生成器 (generator)](https://www.learnpython.org/en/Generators) - [修飾器 (decorator)](https://www.learnpython.org/en/Decorators) ---- ### 列表操作 普通且直觀的方法 ```python sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_lengths = [] for word in words: if word != "the": word_lengths.append(len(word)) print(words) print(word_lengths) ``` ---- ### 列表生成 (list comprehensions) ```python sentence = "the quick brown fox jumps over the lazy dog" words = sentence.split() word_lengths = [len(word) for word in words if word != "the"] print(words) print(word_lengths) ``` --- ## Reference - https://www.python.org/downloads/ - https://github.com/pyenv/pyenv - https://docs.python.org/zh-tw/3/tutorial/index.html - https://www.w3schools.com/python/ - https://www.learnpython.org/ - https://github.com/gto76/python-cheatsheet ---- - https://docs.python.org/3/library/string.html?highlight=formatting#format-string-syntax - https://towardsdatascience.com/why-doesnt-python-support-i-increment-syntax-ca7f04a2beb - https://www.learnpython.org/en/Loops --- ## 問卷網址 http://gg.gg/0425TP --- ## Thanks for Listening ![](https://i.imgur.com/zLSI2im.png) ![](https://i.imgur.com/ZcxsiIa.png) ![](https://i.imgur.com/l0e594e.png)
{"metaMigratedAt":"2023-06-15T10:30:52.639Z","metaMigratedFrom":"YAML","title":"Happy Python Day","breaks":true,"description":"Happy Python Day","lang":"zh-tw","dir":"ltr","robots":"index, follow","GA":"UA-119880828-2","disqus":"ss8651twtw","slideOptions":"{\"transition\":\"slide\"}","contributors":"[{\"id\":\"db4f0000-df30-46e6-b8e1-e38dca2b241f\",\"add\":13609,\"del\":4102}]"}
    1476 views