from visual import * #在這邊我們輸入了vpython的visual模組,方便我們對向量取絕對值
def max_length(a,b): # def開頭來定義函數,a,b是輸入的變數值
if abs(a > abs(b):
return a # 用return傳回計算的絕對值較大者,回到呼叫程式呼叫的地方。
elif abs(b) > abs(a):
return b # 用return傳回計算的絕對值較大者,回到呼叫程式呼叫的地方。
else:
return 'equal' # 用return傳回字串'equal',回到呼叫程式呼叫的地方。
a, b = 5, -8 # 這是元組(tuple)的用法
print a,b,max_length(a,b) #return傳回計絕對值較大者在這邊呈現
c = vector(3,4,5) # c,d是透過vpython visual模組定義的兩個向量
d = vector(2,8,7)
print c,d,max_length(c,d) # return傳回計算向量之絕絕對值較大者在這邊呈現
e = 5+3j # e,f是兩個複數
f = 3+5j
print e,f,max_length(e,f) # return傳回計算複數之絕絕對值較大者在這邊呈現
2. 計算兩整數的公因數。
下面的程式定義了一個計算最大公因數的函數。
def computeHCF(x,y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
print("The H.C.F. of", num1, "and", num2, "is", computeHCF(num1, num2))
def rt(a):
for n in range(1,a+1):
print('*'*n)
while True:
b=input("input the number of lines for the triangle=")
if(b == 0): print 'none'; break
c=int(b)
rt(c)
from visual import *
scene = display(width=800, height=800, center=(0,0,0),background=(0.5,0.5,0))
def traject(tr):
ball = sphere(radius = 0.1, color=(1,0,0),make_trail=True,trail_type="points",
interval=1, retain=200)
arrX=arrow(pos=(0,0,0),axis=(5,0,0),shaftwidth=0.04,color=(1,0,0))
arrY=arrow(pos=(0,0,0),axis=(0,5,0),shaftwidth=0.04,color=(0,1,0))
arrZ=arrow(pos=(0,0,-5),axis=(0,0,10),shaftwidth=0.04,color=(0,0,1))
f=open(tr,'r')
a=f.read()
print a
b=a.split()
Nb=len(b)
N=Nb/4
t=[float(b[i*4+0]) for i in range(N)]
x=[float(b[i*4+1]) for i in range(N)]
y=[float(b[i*4+2]) for i in range(N)]
z=[float(b[i*4+3]) for i in range(N)]
ball.pos=vector(x[0],y[0],z[0])
print ball.pos
for i in range(N):
rate(10)
ball.pos=vector(x[i],y[i],z[i])
print t[i],x[i],y[i],z[i]
traject('spiral-tr.txt')
#traject('mag-bottle-tr.txt')
#traject('projectile-tr.txt')
6. 自行建立模組與簡易應用。
首先編寫了一個儲存許多物理常數的python程式(constants.py)。
在 Python 中,模組是幾個重要抽象層的機制之一,也許是最自然的機制之一,只要你建立了一個原始碼檔案 modu.py,你就建立了一個模組 modu,原始碼主檔名就是模組名稱。 import modu 陳述句會在相同目錄下尋找 modu.py,如果沒找到,則會試著尋找在 sys.path 中遞迴地尋找 modu.py,如果還是沒有,則會引發 ImportError 例外。
模組提供了名稱空間。模組中的變數、函式與類別,基本上需透過模組的名稱空間來取得。在 Python 中,import, import as 與 from import 是陳述句,可以出現在程式中陳述句可出現的任何位置,它們基本上用來在現有範疇(Scope)中匯入、設定名稱空間,舉例來說,如果先前程式範例是撰寫於 constants.py 檔案中,那麼以下是一些 import、import as 與 from import 的使用實例,假設這些程式是撰寫在與 constants.py 相同目錄的另一個 main.py 檔案:
main.py(主程式)的內容如下: