MiniBitePython - #1 Create python .py script | 創建Python腳本
疫情反覆,當大家安在家中,有沒有想學點什麼?
我在工作時有同事問起有關初學 Python 時的問題,希望可以有一些實用點的方式來學習,可惜網上缺少這種資訊。(說穿了是不太會使用Google)。所以我想創一個 Series,搞點簡單的 use case 來讓他學習。以下是系列記錄。以下合適知曉如何使用Terminal的朋友。
1. Create .py file | 創建 .py 檔案
First off, we need to open the terminal and type in
touch sum_num.py
and press the return
button on your keyboard to create a new .py file named sum_num
.
首先,我們需要打開終端並輸入
touch sum_num.py
以創建一個名為sum_num
的新.py
文件。
Then you will see a test.py
file you just created appears on the directory you are currently at.
然後您會看到剛剛創建的
sum_num.py
文件出現在當前目錄中。
2. Edit the blank .py file | 編輯空白的.py文件
To edit the newly created file, you will need a text editor to do so. Here I suggest using VS code from Microsoft. It is an open-source popular text editor.
要編輯新創建的文件,您將需要文本編輯器來執行此操作。 在這裡,我建議使用Microsoft的VS Code。 它是一個開源又很流行的文本編輯器。
for the above code,
def main(num):
defined a function calledmain
that takesnum
as it parameters for further use.sum
created a variable that was set to have0
int value.Here we have a for-loop with a range length of
num
which was supposed to be passed down from themain
function call from line 8, and it is100
.In each loop, we add the new value
i
to thesum
variable.After the for-loop ended, we print the
sum
result to the terminal.
7-8. For the script to be able to run properly in the terminal. We need lines 7-8. And it is a good practice to put code line 7 since we are running THE script. For more info about why: https://stackoverflow.com/questions/28336627/if-name-main-python
The result is 4950. Try it with your calculator!
1.
def main(num):
定義了一個名為main
的函數,該函數將num
作為其參數供進一步使用。
2.創建了一個名為
sum
的變量,該變量被設置為0
int值。
3.在這裡,我們有一個for循環,其範圍長度為
num
,從第8行的main
函數調用中向下傳遞,在這個 example 中數值為100
。
4.在每個循環中,我們將新值
i
添加到sum
變量中。
- for循環結束後,我們將
sum
使用print()
把結果打印到終端。
7-8。 為了使腳本能夠在終端中正常運行。 我們需要 line 7-8。 由於我們正在運行腳本,因此最好在代碼行7中放置。想知道為什麼可以看看這裡: https://stackoverflow.com/questions/28336627/if-name-main-python
結果為4950。
Summary:
We learned to create .py file, edit the blank .py file with a text editor and to write a simple python script.
摘要:
我們學會了創建.py文件,使用文本編輯器編輯空白.py文件以及編寫簡單的python腳本。
Cheers!