CS50P 4_Library

Modules

A module is a file containing Python definitions and statements.

ilename.py --> filename is the module name

__name__ is the global variable of module name

Python 標準函式庫

Random Module

Generate pseudo-random numbers

using module

import random # import random package
print(random.random())
coin = random.choice(["heads", "tails"])
print(coin)
# import specific module in random
from random import random, choice 
print(random())
coin = choice(["heads", "tails"])
print(coin)
from random import * # import all module in random
print(random())
coin = choice(["heads", "tails"])
print(coin)

random() 產生 [0.0, 1.0)之間的隨機浮點數

from random import random
for i in range(5):
    print(f"random() {random()}")
random() 0.7793488239788828
random() 0.869568326885313
random() 0.8821685702670976
random() 0.9777859355580868
random() 0.006675999828335

randint(a, b) 產生一個[a, b]區間內的隨機整數。

import random
for i in range(5):
    number = random.randint(1,10)
    print(number)
3
5
7
10
3

random.shuffle(x) 使序列 x 重新隨機排列

import random
cards = ["acce","jack", "queen", "king", "ghost"]
print(f"original {cards}")
random.shuffle(cards)
print(f"shuffled {cards}")
original ['acce', 'jack', 'queen', 'king', 'ghost']
shuffled ['king', 'ghost', 'queen', 'jack', 'acce']

random.choice(x) 從序列 x 中隨機取出一個元素

import random
for i in range(3):
    fruit = rendom.choice(['apple', 'pear', 'banana'])
    print(f"You need {fruit}")
You need pear
You need banana
You need apple

random.sample(x, k) 從序列 x 中隨機取出k個元素

import random
cities = ["台北", "桃園", "新竹", "台中", "台南"]
for i in range(1,5):
    if i == 1:
        print(f"selec {i} city   {random.sample(cities, i)}")
    else:
        print(f"selec {i} cities {random.sample(cities, i)}") 
selec 1 city   ['桃園']
selec 2 cities ['台中', '新竹']
selec 3 cities ['台南', '台北', '台中']
selec 4 cities ['台南', '新竹', '桃園', '台北']

sys.argv 命令列參數

python test.py aaa 123 ccc
aaa 123 ccc --> 命令列參數

import sys
# 查看 sys.argv 列表內容
print("sys.argv 內容:", sys.argv)
# 第 1 個參數
print("第 1 個參數:", sys.argv[1])
python test.py aaa 123 ccc
sys.argv 內容: ['test.py', 'aaa', '123', 'ccc']
第 1 個參數: aaa

IndexError

import sys
# 查看 sys.argv 列表內容
print("sys.argv 內容:", sys.argv)
# 第 1 個參數
print("第 1 個參數:", sys.argv[1])
$python test.py
sys.argv 內容: ['test.py']
Traceback (most recent call last):
  File "/workspaces/87635444/test/libraries/test.py", line 5, in <module>
    print("第 1 個參數:", sys.argv[1])
IndexError: list index out of range

catch IndexError

import sys
# 查看 sys.argv 列表內容
print("sys.argv 內容:", sys.argv)
try:
    # 第 1 個參數
    print("第 1 個參數:", sys.argv[1])
except IndexError:
    print("命令列參數太少")
$ python test.py
sys.argv 內容: ['test.py']
命令列參數太少

檢查命令列參數的個數

import sys

if len(sys.argv)<2:
    print("Too few arguments")
elif len(sys.argv)>2:
    print("Too many arguments")
else:
    print("hello, my name is", sys.argv[1])
$ python test1.py
Too few arguments
$ python test1.py Ted
hello, my name is Ted
$ python test1.py Ted John
Too many arguments

Install package

import cowsay
import sys

if len(sys.argv) == 2:
    cowsay.cow("hello, " + sys.argv[1])
$ python cowsay1.py 
Traceback (most recent call last):
  File "/workspaces/87635444/test/libraries/cowsay1.py", line 3, in <module>
    import cowsay
ModuleNotFoundError: No module named 'cowsay'

install cowsay package

$ pip install cowsay
Defaulting to user installation because normal site-packages is not writeable
Collecting cowsay
  Downloading cowsay-5.0.tar.gz (25 kB)
  Preparing metadata (setup.py) ... done
Building wheels for collected packages: cowsay
  Building wheel for cowsay (setup.py) ... done
  Created wheel for cowsay: filename=cowsay-5.0-py2.py3-none-any.whl size=25707 sha256=b7b6c79d001b61e366e77574029aa4390c449dfae48ad63707bac412efbd8729
  Stored in directory: /tmp/pip-ephem-wheel-cache-mwurcbqt/wheels/5b/15/b9/15cb7194fd1eae6f630f6d7946fc5160b096a92eafb685c2dd
Successfully built cowsay
Installing collected packages: cowsay
Successfully installed cowsay-5.0

cowsay.cow

import cowsay
import sys

if len(sys.argv) == 2:
    cowsay.cow("hello, " + sys.argv[1])
$ python cowsay1.py Ted
  __________
| hello, Ted |
  ==========
          \
           \
             ^__^
             (oo)\_______
             (__)\       )\/\
                 ||----w |
                 ||     ||
                 

cowsay.tux

import cowsay
import sys

if len(sys.argv) == 2:
    cowsay.tux("hello, " + sys.argv[1])
test/libraries/ $ python cowsay2.py Ted
  __________
| hello, Ted |
  ==========
               \
                \
                 \
                  .--.
                 |o_o |
                 |:_/ |
                //   \ \
               (|     | )
              /'\_   _/`\
              \___)=(___/

Install Request Package

pip install requests

using Requests method

import requests
web = requests.get('https://water.taiwanstat.com/')  # 使用 get 方法
print(web.text)    # 讀取並印出 text 屬性
test/libraries/ $ python request.py
<!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"lang="zh-TW">
<head><meta property="og:title" content="台灣水庫即時水情">
....

Request json

import sys
import requests

if len(sys.argv) != 2:
    sys.exit()

response = requests.get(
    "https://itunes.apple.com/search?entity=song&limit=1&term=" + sys.argv[1]
)
print(response.json())

json.dumps

import json
import sys
import requests

if len(sys.argv) != 2:
    sys.exit()

response = requests.get(
    "https://itunes.apple.com/search?entity=song&limit=1&term=" + sys.argv[1]
)
print(json.dumps(response.json(), indent=2))

json.dumps

test/libraries/ $ python itune2.py jazz
{
  "resultCount": 1,
  "results": [
    {
      "wrapperType": "track",
      "kind": "song",
      "artistId": 161541223,
      "collectionId": 1467951962,
      "trackId": 1467952309,
      "artistName": "Gotye",
      "collectionName": "Making Mirrors (Deluxe Version)",
      "trackName": "Somebody That I Used to Know (feat. Kimbra)",
      "collectionCensoredName": "Making Mirrors (Deluxe Version)",
      "trackCensoredName": "Somebody That I Used to Know (feat. Kimbra)",
      "artistViewUrl": "https://music.apple.com/us/artist/gotye/161541223?uo=4",
      "collectionViewUrl": "https://music.apple.com/us/album/somebody-that-i-used-to-know-feat-kimbra/1467951962?i=1467952309&uo=4",
      "trackViewUrl": "https://music.apple.com/us/album/somebody-that-i-used-to-know-feat-kimbra/1467951962?i=1467952309&uo=4",
      "previewUrl": "https://audio-ssl.itunes.apple.com/itunes-assets/AudioPreview125/v4/a5/ff/2f/a5ff2fdd-11b3-698f-67e6-f49cad28df6e/mzaf_15135349959596902883.plus.aac.p.m4a",
      "artworkUrl30": "https://is2-ssl.mzstatic.com/image/thumb/Music125/v4/32/41/fe/3241fe70-3529-2060-7212-48cd0cccbe6e/11UMGIM19347.rgb.jpg/30x30bb.jpg",
      "artworkUrl60": "https://is2-ssl.mzstatic.com/image/thumb/Music125/v4/32/41/fe/3241fe70-3529-2060-7212-48cd0cccbe6e/11UMGIM19347.rgb.jpg/60x60bb.jpg",
      "artworkUrl100": "https://is2-ssl.mzstatic.com/image/thumb/Music125/v4/32/41/fe/3241fe70-3529-2060-7212-48cd0cccbe6e/11UMGIM19347.rgb.jpg/100x100bb.jpg",
      "collectionPrice": 16.99,
      "trackPrice": 0.69,
      "releaseDate": "2011-07-05T12:00:00Z",
      "collectionExplicitness": "notExplicit",
      "trackExplicitness": "notExplicit",
      "discCount": 1,
      "discNumber": 1,
      "trackCount": 12,
      "trackNumber": 3,
      "trackTimeMillis": 244973,
      "country": "USA",
      "currency": "USD",
      "primaryGenreName": "Alternative",
      "isStreamable": true
    }
  ]
}

get attribute from jason

import json
import sys
import requests

if len(sys.argv) != 2:
    sys.exit()

response = requests.get(
    "https://itunes.apple.com/search?entity=song&term=" + sys.argv[1]
)
o = response.json()
for result in o["results"]:
    print(result["trackName"])

get attribute from jason

$ python itune2.py jazz
Somebody That I Used to Know (feat. Kimbra)
Bad Day
Home
What a Wonderful World
Jazz
Feeling Good
The Way You Look Tonight
...

__name__

tools.py
def main():
    print(f"tolols test {tool_1()}")
    print(f"tolols test {tool_2()}")
 
def tool_1():
    return "you use tool1"
def tool_2():
    return "you use tool2"

main()
print(f"tools.py __name__ is {__name__}")
$ python tools.py
tolols test you use tool1
tolols test you use tool2
tools.py __name__ is __main__

use tools module

use_tools.py
import tools
print(f"use_tools  {tools.tool_1()}")
test/libraries/ $ python use_tools.py 
tolols test you use tool1
tolols test you use tool2
tools.py __name__ is __main__
use_tools you use tool1

prevent use_tool run tha main()

def main():
    print(f"tolols test {tool_1()}")
    print(f"tolols test {tool_2()}")
 
def tool_1():
    return "you use tool1"
def tool_2():
    return "you use tool2"

if __name__ == '__main__':
    main()
print(f"tools.py __name__ is {__name__}")
test/libraries/ $ python use_tools.py 
tolols test you use tool1
tolols test you use tool2
tools.py __name__ is __main__

use tools module

use_tools.py
import tools
print(f"use_tools  {tools.tool_1()}")
$ python use_tools.py 
__name__ is tools
you use tool1

request example

臺灣證券交易所 每日收盤行情

CS50P 4_Library

By wschen

CS50P 4_Library

Learn about the CS50P 4_Library and the Python standard library. Explore the Random module and how to generate pseudo-random numbers. Discover useful functions like randint, shuffle, choice, and sample. Understand how to handle command line arguments and catch errors. Install packages like cowsay and use the Requests module to work with JSON data.

  • 88