【練習題】第五章--條件迴圈(Think Python)
阿新 • • 發佈:2018-11-06
//--地板除。例:5//4=1
%--求模。例:5//3=2
如果你用Python2的話,除法是不一樣的。在兩邊都是整形的時候,常規除法運算子/就會進行地板除法,而兩邊只要有一側是浮點數就會進行浮點除法。
複合語句中語句體內的語句數量是不限制的,但至少要有一個。有的時候會遇到一個語句體內不放語句的情況,比如空出來用來後續補充。這種情況下,你就可以用pass語句,就是啥也不會做的。
if x < 0:
pass
if x < y: print('x is less than y') elif x > y: print('x is greater than y') else: print('x and y are equal')
Python提供了更簡潔的表達方法:
if 0 < x < 10:
print('x is a positive single-digit number.')
呼叫自身的函式就是遞迴的;執行這種函式的過程就叫遞迴運算。
in python3:
>>> text = input()
in python2:
>>> text = raw_input()
input函式能夠把提示內容作為引數:
>>> name = input('What...is your name?\n') What...is your name?
如果你想要使用者來輸入一個整形變數,可以把返回的值手動轉換一下:
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
42
>>> int(speed)
42
練習1:
time模組提供了一個名字同樣叫做time的函式,會返回當前格林威治時間的時間戳,就是以某一個時間點作為初始參考值。在Unix系統中,時間戳的參考值是1970年1月1號。
(譯者注:時間戳就是系統當前時間相對於1970.1.1 00:00:00以秒計算的偏移量,時間戳是惟一的。)
>>> import time
>>> time.time() 1437746094.5735958
寫一個指令碼,讀取當前的時間,把這個時間轉換以天為單位,剩餘部分轉換成小時-分鐘-秒的形式,加上參考時間以來的天數。
code:
import time
D=time.time()//(60*60*24)
H=(time.time()%(60*60*24))//(60*60)
M=(time.time()%(60*60*24))%(60*60)//60
S=(time.time()%(60*60*24))%(60*60)%60
print('The time is %dD-%dH-%dM-%S',D,H,M,S)