# 在 Python 中建立倒數計時器

## 在 Python 中使用 `time` 模組和 `sleep()` 函式建立倒數計時器

`time` 模組是一個通用的 Python 模組，包含與時間相關的實用函式和變數。本教程中使用的主要函式是 `sleep()` 函式，它是一個非同步函式，可將單個執行緒的執行暫停 `n` 秒。

``````import time
``````

`num_of_secs` 變數將在迴圈中不斷遞減，直到達到 `0`（轉換為 `False` 並在沒有任何額外條件的情況下結束迴圈）。

``````def countdown(num_of_secs):
while num_of_secs:
m, s = divmod(num_of_secs, 60)
min_sec_format = "{:02d}:{:02d}".format(m, s)
``````

`{:02d}` 將引數格式化為 2 位整數（因為符號 `02d`）。如果整數小於 2 位，它將新增前導 `0`

``````def countdown(num_of_secs):
while num_of_secs:
m, s = divmod(num_of_secs, 60)
min_sec_format = "{:02d}:{:02d}".format(m, s)
print(min_sec_format, end="/r")
time.sleep(1)
num_of_secs -= 1

print("Countdown finished.")
``````

``````inp = input("Input number of seconds to countdown: ")
countdown(int(inp))
``````

``````import time

def countdown(num_of_secs):
while num_of_secs:
m, s = divmod(num_of_secs, 60)
min_sec_format = "{:02d}:{:02d}".format(m, s)
print(min_sec_format, end="/r")
time.sleep(1)
num_of_secs -= 1

print("Countdown finished.")

inp = input("Input number of seconds to countdown: ")
countdown(inp)
``````

``````Countdown finished.
``````

``````00:05
00:04
00:03
00:02
00:01
Countdown finished.
``````

Skilled in Python, Java, Spring Boot, AngularJS, and Agile Methodologies. Strong engineering professional with a passion for development and always seeking opportunities for personal and career growth. A Technical Writer writing about comprehensive how-to articles, environment set-ups, and technical walkthroughs. Specializes in writing Python, Java, Spring, and SQL articles.