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文件。

image.png

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。 它是一個開源又很流行的文本編輯器。

image.png

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: https://stackoverflow.com/questions/28336627/if-name-main-python

image.png

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變量中。

  1. 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!



0
0
0.000
0 comments