A module is a file containing Python definitions and statements.
filename.py --> filename is the module name
__name__
is the global variable of module name
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)
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
import random
for i in range(5):
number = random.randint(1,10)
print(number)
3
5
7
10
3
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']
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
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 ['台南', '新竹', '桃園', '台北']
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
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
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
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'
$ 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
import cowsay
import sys
if len(sys.argv) == 2:
cowsay.cow("hello, " + sys.argv[1])
$ python cowsay1.py Ted
__________
| hello, Ted |
==========
\
\
^__^
(oo)\_______
(__)\ )\/\
||----w |
|| ||
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
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="台灣水庫即時水情">
....
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())
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))
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
}
]
}
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"])
$ 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__
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
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__
import tools
print(f"use_tools {tools.tool_1()}")
$ python use_tools.py
__name__ is tools
you use tool1
臺灣證券交易所 每日收盤行情