Skip to content

Latest commit

 

History

History
150 lines (91 loc) · 11.4 KB

File metadata and controls

150 lines (91 loc) · 11.4 KB

Your First Python Program

In the previous lesson, we learned about the past and present of Python, and we prepared the interpreter environment needed to run Python programs. I believe everyone is already eager to start their own Python programming journey, but a new question comes: where should we write Python programs, and how should we run them?

Tools for Writing Code

Below we will explain several tools that can be used to write and run Python code. Everyone can choose a suitable tool according to their own needs. Of course, for beginners, I personally recommend PyCharm, because it does not need much configuration and it is also very powerful, so it is friendly to beginners. If you already know PyCharm or already like it, you can skip the introduction to the other tools below and jump straight to the part about PyCharm.

The Default Interactive Environment

Open Windows Command Prompt or PowerShell, enter python, and then press the Enter key. This command takes us into an interactive environment. An interactive environment means that we enter one line of code and press Enter, and the code runs at once. If the code produces a result, the result is shown in the window, as shown below.

Python 3.10.10
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 * 3
6
>>> 2 + 3
5
>>>

Note: Users of macOS need to open Terminal and enter python3 to enter the interactive environment.

If you want to leave the interactive environment, you can enter quit() in the interactive environment, as shown below.

>>> quit()

A Better Interactive Environment - IPython

The interactive environment mentioned above does not have a very good user experience, and you can feel that after trying it. We can replace it with IPython, because IPython provides more powerful editing and interaction features. We can use Python's package management tool pip in Command Prompt or Terminal to install IPython, as shown below.

pip install ipython

Tip: Before using the command above to install IPython, you can first use pip config set global.index-url https://pypi.doubanio.com/simple or pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple/ to change the download source to the Douban mirror or Tsinghua mirror in China. Otherwise, downloading and installing may be very slow.

Next, you can use the command below to start IPython and enter the interactive environment.

ipython

Note: There is also a web version of IPython called Jupyter. We will introduce it when we need to use it.

A Great Text Editor - Visual Studio Code

Visual Studio Code is an excellent code editor developed by Microsoft. It can run on Windows, Linux, macOS, and other operating systems. It supports syntax highlighting, auto-completion, multi-cursor editing, running, debugging, and many other convenient features, and it supports many programming languages. If you want to choose an advanced text editor, I strongly recommend Visual Studio Code. Readers who are interested can study its download, installation, and usage by themselves.

Integrated Development Environment - PyCharm

If you use Python to develop commercial projects, we recommend the more professional tool PyCharm. PyCharm is an integrated development environment (IDE) for Python provided by a Czech company named JetBrains. An integrated development environment usually means a development tool that provides powerful features and convenient operations such as writing code, running code, debugging code, analyzing code, and version control, so it is especially suitable for commercial projects. We can find the download link for PyCharm on the official website of JetBrains, as shown in the picture below.

The official site provides two versions of PyCharm. One is the free Community Edition. Its features are relatively weaker, but for beginners it is completely enough. The other is the paid Professional Edition. It is very powerful, but you need to pay by year or by month. New users can try it for free for 30 days. Installing PyCharm is not difficult at all. Run the downloaded installer, and you can keep the default settings for almost everything. For Windows users, one step can be set as shown in the picture below by checking Create Desktop Shortcut and Add "Open Folder as Project" to the right-click menu.

When you run PyCharm for the first time, on the screen that asks you to import PyCharm settings, directly choose Do not import settings, and then you will see the welcome screen shown in the picture below. Here, we can first click Customize to make some personal settings for PyCharm.

Next, in the Projects section, we can click New Project to create a new project. Here you can also open an existing project or get a project from a version control server (VCS), as shown in the picture below.

When creating a project, you need to specify the project path and create a virtual environment. We recommend that every Python project run in its own virtual environment. If your system still does not have a Python environment, PyCharm will provide a download link to the official website. When you click the Create button to create the project, it will download the Python interpreter from the internet, as shown in the picture below.

Of course, we do not recommend doing this, because we already installed the Python environment in the previous lesson. When the system already has a Python environment, PyCharm will usually find the location of the Python interpreter automatically and create a virtual environment based on it, so the screen you see should look like the picture below.

Note: The screenshots above come from Windows. If you use macOS, the project path and Python interpreter path you see will be different from above.

After the project is created, the screen shown in the picture below will appear. We can right-click the project folder, choose New, and then choose Python File to create a Python file. When naming the file, it is recommended to use a combination of English letters and underscores. The new Python file will open automatically and be ready for editing.

Next, we can write our Python code in the code window. After writing the code, we can right-click in the window and choose the Run menu item to run it. The Run window below will show the result, as shown in the picture below.

At this point, our first Python program is already running. Very cool, right? By the way, PyCharm has a pop-up window called Tip of the Day. It teaches you some small tips for using PyCharm, as shown in the picture below. If you do not need it, just close it. If you do not want it to appear again, you can check Don't show tips on startup before closing it.

Hello, World

According to industry practice, the first program we write when learning any programming language is to print hello, world, because this line of code was the first code written by the great Dennis Ritchie (the father of the C language, who developed the Unix operating system together with Ken Thompson) and Brian Kernighan (the inventor of the awk language) in their immortal book The C Programming Language. Below is the Python version.

print('hello, world')

Note: The parentheses and single quotes in the code above must be entered in English input mode. If you accidentally use Chinese parentheses or Chinese single quotes, errors such as SyntaxError: invalid character '(' (U+FF08) or SyntaxError: invalid character '‘' (U+2018) will appear when you run the code.

The code above has only one statement. In this statement, we use a function named print, and it helps us output the specified content. The 'hello, world' inside the parentheses of the print function is a string, and it represents a piece of text. In Python, we can use single quotes or double quotes to represent a string. Unlike programming languages such as C, C++, or Java, statements in Python do not need semicolons at the end. In other words, if we want to write another statement, we only need to press Enter and start a new line, as shown below. Also, Python code does not need an entry function named main in order to run. Providing an entry function is something that must be done when writing executable C, C++, or Java code, and many programmers are familiar with that, but in Python it is not necessary.

print('hello, world')
print('goodbye, world')

If we do not use an integrated development environment like PyCharm, we can also call the Python interpreter directly to run a Python program. We can save the code above as a file named example01.py. On Windows, let us suppose the file is under C:\code. We open Command Prompt or PowerShell and enter the command below to run it.

python C:\code\example01.py

On macOS, suppose our file is under /Users/Hao, then we can enter the command below in Terminal to run the program.

python3 /Users/Hao/example01.py

Tip: If the path is long and you do not want to type it by hand, you can drag the file directly into Command Prompt or Terminal, and the full file path will be entered automatically.

You can try changing the code above. For example, replace hello, world inside the single quotes with other content, or write a few more statements like this, and then see what result you get. One reminder is that when writing Python code, it is best to write only one statement on each line. Although we can use ; as a separator to write multiple statements on one line, doing so makes the code look very ugly and hurts readability.

Comment Your Code

Comments are an important part of programming languages. They are used to explain what the code does, so they improve readability. Of course, we can also use comments to disable code that does not need to run for the moment. Then, when you need to use that code again, you only need to remove the comment markers. Simply speaking, comments make the code easier to understand, but they do not affect the execution result.

Python has two forms of comments:

  1. Single-line comments: start with # and a space, and can comment out the whole line after #.
  2. Multi-line comments: start with triple quotes (usually double quotes) and end with triple quotes, and are usually used for multi-line explanatory content.
"""
Your first Python program - hello, world

Version: 1.0
Author: Luo Hao
"""
# print('hello, world')
print("Hello, world!")

Summary

At this point, we have already run our first Python program. Doesn't it feel satisfying? As long as you keep learning, before long, we will be able to use Python to do more and cooler things. In today's world, programming is just like English. For many people, it is a skill that must be mastered.