by 李至青
借用別人的功能、收納你的程式碼
import random
random.random()
0.4668728680655134
random.randint(1,100)
13
python -V / python3 -V
# words.py
GREETING = '大家早安!'
THANKS = '謝謝大家'
MYNAME = '李至青'
MYPRO = '開發網頁'
-----------------------
# main.py
import words# 不用加副檔名
print(words.MYNAME)
print(words.THANKS)
print(words.MYPRO)
print(words.GREETING)
from words import GREETING
GREETING
'大家早安!'
import words as w # 使用縮寫時機為:1. 讓語法更簡便 2. 避免命名衝突
w.GREETING
'大家早安!'
# opening.py
import words
def say():
print(words.GREETING + '我是' + words.MYNAME + ',喜歡' + words.MYPRO)
# ending.py
import words
def say():
print(words.THANKS + ' by ' + words.MYNAME)
# main.py
import opening
import ending
opening.say()
ending.say()
大家早安!我是李至青,喜歡開發網頁 謝謝大家 by 李至青
.
├── ending.py # 定義結束函式
├── words.py # 定義用詞字串
├── opending.py # 定義開場函式
└── main.py # 程式進入點
# config.py
range1 = [1, 9]
range2 = [1, 9]
--------------------------------------
# calc.py
def calc(a,b):
return [
{'sign': '*', 'result':a*b},
];
--------------------------------------
# main.py
import config
import calc
for i in range(config.range1[0], config.range1[1] + 1):
for j in range(config.range2[0], config.range2[1] + 1):
for k in calc.calc(i, j):
print(str(i) + str(k['sign']) + str(j) + '=' + str(k['result']), end=" ")
print()
say/
├── __init__.py
├── hello.py
├── sorry.py
└── bye.py
# __init__.py
import say.hello
import say.bye
import say.sorry
# hello.py
def cht():
print('哈摟!')
def en():
print('hello!')
def se():
print('Hej!')
import say
say.hello.se()
Hej!
from say import hello
hello.cht()
哈摟!
dir(say)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'bye', 'hello', 'say', 'sorry']
dir(say.sorry)
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'cht', 'en', 'se']
say.sorry.en()
sorry
help('modules')