MiniBitePython - #1 Create python .py script | 創建Python腳本

in hive-105017 •  20 days ago 

我在工作時有同事問起有關初學 Python 時的問題,希望可以有一些實用點的方式來學習,可惜網上缺少這種資訊。(說穿了是不太會使用Google)。所以我想創一個 Series,搞點簡單的 use case 來讓他學習。以下是系列記錄。以下合適知曉如何使用Terminal的朋友。

1. Create .py file | 創建 .py 檔案

First off, we need to open the terminal and type in
touch 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 file you just created appears on the directory you are currently at.


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,

  1. def main(num): defined a function called main that takes num as it parameters for further use.

  2. sum created a variable that was set to have 0 int value.

  3. Here we have a for-loop with a range length of num which was supposed to be passed down from the main function call from line 8, and it is 100.

  4. In each loop, we add the new value i to the sum variable.

  5. 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:


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


  1. for循環結束後,我們將sum使用 print()把結果打印到終端。

7-8。 為了使腳本能夠在終端中正常運行。 我們需要 line 7-8。 由於我們正在運行腳本,因此最好在代碼行7中放置。想知道為什麼可以看看這裡:



We learned to create .py file, edit the blank .py file with a text editor and to write a simple python script.



Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!