如何使用Python

入門篇

Hello World!

環境準備結束後就可以來寫代碼了!

首先要先打開任何一個可以寫文章的資料夾,然後把這個資料夾的名稱改成「任意名稱.py」。要注意副檔名的部分一定要是「.py」!這邊就先把檔名儲存成「hello.py」試試看吧!

我使用的編輯軟體是「Visual Studio Code」,這也是很多人在寫程式時會用的軟體。如果想下載的話可以點下面連結!當然除了Visual Studio Code以外也有很多軟體可以使用。最簡單的就是電腦中內建的記事本。

Download Visual Studio Code - Mac, Linux, Windows
Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows. Download Visual Studio Code to experience a redefined code edit

接著在你的編輯軟體中寫下下面的代碼。

print('Hello World!')

接著就是叫出你的終端機(Windows人請叫出命令提示字元)移動到目前檔案的位置之後輸入「python hello.py」,代碼就會被執行了。(在終端機輸入$之後的文字就會被執行)

$ python hello.py
#執行結果
Hello World!

執行之後會出現下面的樣子。

這邊要注意的是打開終端機之後要先確認「hello.py」這個檔案的位置。必須把終端機的path移動至跟hello.py一樣才有辦法執行代碼。如果不知道檔案的確切位置的話可以對檔案點右鍵之後點選「內容」,就可以確認位置了。

之後只要複製檔案的絕對位置,到終端機上面輸入下面的代碼就可以了。

cd /Users/Desktop/.../hello.py

Python的基礎

在使用Python的時候有幾個要注意的地方。

Indent

Python的其中的一個特徵是indent。indent是指在句子的開頭插入一個空格(通常為2個半形空白鍵或是tab鍵)把第一個字母往右邊推。

其他語言例如C, C++, Java, PHP等等比較少利用到indent,不過Python的場合是將indent視作一個區塊。

如果indent不小心少打或是多打了,可能會執行錯誤的處理或是失敗。

Comment

在每個語言之中都有Comment。Python的Comment是「#」。Comment代表的意思是在「#」之後的代碼或是文章都不會被執行。在寫代碼的說明的時候經常會用到。

留言

  1. An interesting discussion is definitely worth comment. I believe that you need to publish more on this issue, it might not be a taboo matter but
    generally folks don’t discuss such subjects. To the next!
    Kind regards!!

  2. Way cool! Some very valid points! I appreciate you writing this write-up and the
    rest of the site is extremely good.

  3. best cbd lube表示:

    Hello this is kinda of off topic but I was wanting to know if blogs
    use WYSIWYG editors or if you have to manually code with HTML.
    I’m starting a blog soon but have no coding knowledge so I wanted to
    get advice from someone with experience. Any help would be greatly appreciated!