Python programming entry to practice

Chapter 1 Getting Started

In this chapter, you will run your first program-hello_world.py. To do this, you first need to check whether Python is installed on your computer; if it is not installed, you need to install it. You also need to install a text editor for writing and running Python programs. When you enter Python code, this text editor can recognize them and highlight different parts, allowing you to easily understand the structure of the code.

1.1 Setting up a programming environment

In different operating systems, Python has subtle differences, so there are a few things you need to keep in mind. Here will introduce the two main Python versions you use, and briefly introduce the installation steps of Python.

1.1.1 Python 2 and Python 3

Currently, there are two different Python versions: Python 2 and the newer Python 3. Each programming language will continue to evolve with the introduction of new concepts and technologies, and Python developers have been committed to enriching and enhancing its functions. Most of the changes are made step by step, and you hardly realize it, but if your system is installed with Python 3, then some code written in Python 2 may not run correctly. In this book, I will point out the major differences between Python 2 and Python 3 so that no matter which version of Python you have installed, you can follow the instructions in the book.
If your system has these two versions installed, please use Python 3; if you don’t have Python installed, please install Python 3; if only Python 2 is installed, you can also directly use it to write code, but it’s better to upgrade to Python 3 as soon as possible. Good, because then you can use the latest Python version.

1.1.2 Run Python code snippets

Python comes with an interpreter that runs in a terminal window, so you can try to run Python code snippets without saving and running the entire program.
This book will list the code snippets as follows:

>>>print("Hello Python interpreter!")
Hello Python interpreter!

The bold text indicates the code that you need to enter and then press the Enter key to execute. Most of the examples in this book are standalone small programs, and you will execute them in the editor, because most of the code is written this way. However, in order to demonstrate a basic concept efficiently, a series of code snippets need to be executed in a Python terminal session. As long as the code listing contains three angle brackets (as shown by ❶), it means that the output comes from a terminal session. Later, I will demonstrate how to write code in the Python interpreter.

1.1.3 Hello World program

For a long time, the programming world has believed that when you are new to a new language, if you first use it to write a program that displays the message "Hello world!" on the screen, it will bring you good luck.
To use Python to write this kind of Hello World program, only one line of code is required:

print("Hello world!")

This kind of program is simple, but it has a purpose: if it runs correctly on your system, any Python program you write will do. How to write such a program in a specific system will be introduced later.

1.2 Build Python programming environment in different operating systems

Python is a cross-platform programming language, which means it can run on all major operating systems. On all modern computers with Python installed, you can run any Python program you write. However, in different operating systems, there are subtle differences in the method of installing Python.
In this section, you will learn how to install Python and run the Hello World program on your own system. You must first check whether your system has Python installed, if not, install it; next, you need to install a simple text editor and create an empty Python file-hello_world.py. Finally, you will run the Hello World program and troubleshoot various faults. I will introduce in detail how to complete these tasks in various operating systems, so that you can build a beginner-friendly Python programming environment.

1.2.1 Build Python programming environment in Linux system

The Linux system is designed for programming, so in most Linux computers, Python is installed by default. The people who write and maintain Linux think that you are likely to use this system for programming, and they encourage you to do so. In view of this, to program in this kind of system, you hardly need to install any software and hardly need to modify the settings.

  • 1. Check Python version

Run the terminal application on your system (if you are using Ubuntu, press Ctrl+Alt+T) and open a terminal window. To determine whether Python is installed, execute the command python (please note that the p is lowercase). The output will be similar to the following, which indicates the version of Python installed; the last >>> is a prompt that allows you to enter Python commands.

$python
Python 2.7.6 (default, Mar 22 2014, 22:59:38)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

The above output shows that the default Python version used by the current computer is Python 2.7.6. After seeing the above output, if you want to exit Python and return to the terminal window, you can press Ctrl+D or execute the command exit().
To check whether the system has Python 3 installed, you may need to specify the corresponding version. In other words, if the output indicates that the default version is Python 2.7, try executing the command python3:

$python3
Python 3.5.0 (default, Sep 17 2015, 13:05:18)
[GCC 4.8.4] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The above output indicates that Python 3 is also installed on the system, so you can use either of these two versions. In this case, please replace all the commands python in this book with python3. Most Linux systems have Python installed by default, but if your Linux system does not install Python or only Python 2 for some reason, and you want to install Python 3, please Baidu yourself.

  • 2. Install a text editor

Geany is a simple text editor: it is easy to install; allows you to run almost all programs directly (without running through the terminal); uses different colors to display the code to highlight the code syntax; run in the terminal window The code allows you to get used to the terminal. Appendix B introduces some other text editors, but I strongly recommend that you use Geany unless you have a good reason not to do so.
In most Linux systems, you can install Geany with just one command:

$sudo apt-get install geany

If this command does not work, please refer to the instructions at http://geany.org/Download/ThirdPartyPackages/ .

  • 3. Run the Hello World program

To write the first program, Geany needs to be started. To do this, press the Super key (commonly known as the Windows key) and search for Geany in the system. After finding Geany, double-click to start it; then drag it to the taskbar or desktop to create a shortcut. Next, create a folder for storing the project and name it python_work (in the file name and folder name, it is better to use lowercase letters and use underscores to indicate spaces, because this is the naming convention adopted by Python) . Back to Geany, select the menu File Save As, save the current empty Python file to the folder python_work, and name it hello_world.py. The extension .py tells Geany that the file contains a Python program; it also lets Geany know how to run the program and highlights the code in it in a useful way.
After saving the file, enter the following line of code in it:

print(“Hello Python world!”)

If your system has multiple versions of Python installed, you must configure Geany to use the correct version. To do this, select the menu Build (build) Set Build Commands (set build command); you will see the text Compile (compile) and Execute (execute), they have a command next to them. By default, both of these commands are python. To allow Geany to use the command python3, you must make corresponding modifications.
If you can execute the command python3 in the terminal session, please modify the compilation command and the execution command to let Geany use the Python 3 interpreter. To this end, modify the compile command to the following:

python3 -m py_compile “%f”

You must output this command exactly as shown in the code above, making sure that the spaces and capitalization are exactly the same.
Modify the execution command to the following:

python3 “%f”

Also, make sure that the spaces and capitalization are exactly the same as shown. Figure 1-1 shows how to configure these commands in Geany.
[illustration]

Figure 1-1 Configure Geany in Linux to use Python 3

Now let's run the program hello_world.py. To do this, select the menu Build Execute, click the Execute icon (two gears) or press F5. A terminal window will pop up with the following output:

Hello Python world!
------------------
(program exited with code: 0)
Press return to continue

If you don't see this output, please check every character you type. Did you capitalize the first letter of print? Did you miss the quotation marks or brackets? Programming languages ​​have very strict requirements on grammar. As long as you do not strictly follow the grammar, errors will occur. If the code is correct, the program will not run correctly, please refer to section 1.3.

  • 4. Run Python code in a terminal session

You can open a terminal window and execute the command python or python3, and then try to run the Python code snippets. You did this when you checked the Python version. Do this again below, but enter the following line of code in the terminal session:

>>>print("Hello Python interpreter!")
Hello Python interpreter!
>>>

The message will be printed directly to the current terminal window. Don't forget, to close the Python interpreter, you can press Ctrl+D or execute the command exit().

1.2.2 Setting up a Python programming environment in OS X

Most OS X systems have Python installed by default. After confirming that Python is installed, you also need to install a text editor and make sure that its configuration is correct.

  • 1. Check if Python is installed

In the folder Applications/Utilities, select Terminal to open a terminal window; you can also press Command+Spacebar, then type terminal and press Enter. To determine whether Python is installed, execute the command python (note that the p is lowercase). The output will be similar to the following, which indicates the version of Python installed; the last >>> is a prompt that allows you to enter Python commands.

$ python
Python 2.7.5 (default, Mar 9 2014, 22:15:05)
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits", or "license" for more information.
>>>

The above output shows that the default Python version used by the current computer is Python 2.7.5. After seeing the above output, if you want to exit Python and return to the terminal window, you can press Ctrl+D or execute the command exit().
To check whether Python 3 is installed on the system, try to execute the command python3. An error message may appear, but if the output indicates that the system has Python 3 installed, you can use it without installing it. If the command python3 can be executed in your system, please replace the command python3 with all the commands python in this book. If you don’t know why your system does not have Python installed, or only Python 2 is installed, and you want to install Python 3, please Baidu yourself.

  • 2. Run Python code in a terminal session

You can open a terminal window and execute the command python or python3, and then try to run the Python code snippets. You did this when you checked the Python version. Do this again below, but enter the following line of code in the terminal session:

>>>print("Hello Python interpreter!")
Hello Python interpreter!
>>>

The message will be printed directly to the current terminal window. Don't forget, to close the Python interpreter, you can press Ctrl+D or execute the command exit().

3. Install a text editor

Sublime Text is a simple text editor: it is easy to install in OS X; allows you to run almost any program directly (without going through the terminal); uses different colors to display the code to highlight the code syntax; embedded Run the code in a terminal session in the Sublime Text window, allowing you to easily view the output. Appendix B introduces some other text editors, but I strongly recommend that you use Sublime Text unless you have a good reason not to do so.
To download the Sublime Text installer, visit http://sublimetext.com/3, click the Download link, and find the OS X installer. The licensing strategy of Sublime Text is very flexible. You can use this editor for free, but if you like it and want to use it for a long time, it is recommended that you purchase a license. After downloading the installer, open it, and then drag and drop the Sublime Text icon to the Applications folder.

4. Configure Sublime Text to use Python 3

If the command you use to start a Python terminal session is not python, you need to configure Sublime Text to let it know where to find the correct Python version on the system. To get the full path of the Python interpreter, execute the following command:

$ type -a python3
python3 is /usr/local/bin/python3

Now, start Sublime Text, and select the menu Tools>Build System>New System, which will open a new configuration file. Delete all the contents, and then enter the following:

{
“cmd”: ["/usr/local/bin/python3","-u",
“$file”],
}

These codes let Sublime Text use the command python3 to run the files opened by the current generation. Please make sure that the path is the path you learned by using the command type -a python3 in the previous step. Name this configuration file Python3.sublime-build, and save it to the default directory-the directory that Sublime Text opens when you select the menu Save.

5. Run the Hello World program

To write the first program, you need to start Sublime Text. To do this, you can open the folder Applications and double-click the icon Sublime Text; you can also press Command+Spacebar, and then enter sublime text in the pop-up search box.
Create a folder for storing the project and name it python_work (in the file name and folder name, it is best to use lowercase letters and use underscores to indicate spaces, because this is the naming convention adopted by Python). In Sublime Text, select the menu File> Save As, save the current empty Python file to the folder python_work, and name it hello_world.py. The extension .py tells Sublime Text that the file contains a Python program; it also lets Sublime Text know how to run the program and highlights the code in it in a useful way.
After saving the file, enter the following line of code in it:

print(“Hello Python world!”)

If you can run the command python in the system, you can select the menu Tools Build or press Ctrl+B to run the program. If you have configured Sublime Text so that the command it uses is not python, please select the menu Tools Build System, and then select Python 3. This will set Python 3 as the default Python version; after that, you can select the menu Tools Build or press Command+B to run the program.
A terminal screen will appear at the bottom of the Sublime Text window, which contains the following output:

Hello Python world!
[Finished in 0.1s]

If you don't see this output, please check every character you type. Did you capitalize the first letter of print? Did you miss the quotation marks or brackets? Programming languages ​​have very strict requirements on grammar. As long as you do not strictly follow the grammar, errors will occur. If the code is correct, the program will not run correctly, please refer to section 1.3.

1.2.3 Build Python programming environment in Windows system

Not all Windows systems have Python installed by default, so you may need to download and install it, and then download and install a text editor.

  • 1. Install Python

First, check if Python is installed on your system. To do this, enter command in the "Start" menu and press Enter to open a command window; you can also hold down the Shift key and right-click on the desktop, and then select "Open command window here". Enter python in the terminal window and press Enter; if the Python prompt (>>>) appears, it means that Python is installed on your system. However, you may also see an error message stating that python is an unrecognized command.
If so, you need to download the Windows Python installer. To do this, please visit http://python.org/downloads/ . You will see two buttons for downloading Python 3 and Python 2. Click the button for downloading Python 3. This will automatically download the correct installer according to your system. After downloading the installer, run it. Make sure to check the Add Python to PATH checkbox (as shown in Figure 1-2), which allows you to configure the system more easily.
[illustration]

Figure 1-2 Make sure the checkbox Add Python to PATH is checked

  • 2. Start a Python terminal session

By configuring the system so that it can run Python in a terminal session, the configuration of the text editor can be simplified. Open a command window and execute the command python in it. If the Python prompt (>>>) appears, it means that Windows has found the Python version you just installed.

C:\>python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 22:15:05) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

If so, you can skip directly to the next part-"Run Python in a terminal session".
However, the output may be similar to the following:

C:\>python
'python' is not recognized as an internal or external command, operable
program or batch file.

In this case, you must tell Windows how to find the version of Python you just installed. The command python is usually stored in the C drive, so please open the C drive in Windows Explorer, find and open the folder starting with Python in it, and then find the file python. For example, on my computer, there is a folder named Python35, which contains a file named python, so the path of the file python is C:\Python35\python. If you cannot find this file, please enter python in the search box of Windows Explorer, which will allow you to accurately learn where the command python is stored in the system.
If you think you already know the path of the command python, enter the path in the terminal window to test. To do this, open a command window and enter the full path you determined:

 
C:\>C:\Python35\python
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 22:15:05) [MSC v.1900 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>

If it works, it means you already know how to access Python.

  • 3. Run Python in a terminal session

Execute the following command in a Python session and confirm that you see the output "Hello Python world!".

>>>print("Hello Python world!")
Hello Python world!
>>>

Whenever you want to run a snippet of Python code, open a command window and start a Python terminal session. To close the terminal session, you can press Ctrl+Z, then press Enter, or you can execute the command exit().

  • 4. Install a text editor

Geany is a simple text editor: it is easy to install; allows you to run almost all programs directly (without going through the terminal); uses different colors to display the code to highlight the code syntax; run the code in the terminal window, Let you get used to using the terminal. Appendix B introduces some other text editors, but I strongly recommend that you use Geany unless you have a good reason not to do so.
To download the Windows Geany installer, visit http://geany.org/ , click Releases under Download, and find the installer geany-1.25_setup.exe or a similar file. After downloading the installer, run it and accept all the default settings.
To write the first program, Geany needs to be started. To do this, press the Super key (commonly known as the Windows key) and search for Geany in the system. After finding Geany, double-click to start it; then drag it to the taskbar or desktop to create a shortcut. Next, create a folder for storing the project and name it python_work (in the file name and folder name, it is better to use lowercase letters and use underscores to indicate spaces, because this is the naming convention adopted by Python) . Back to Geany, select the menu File> Save As, save the current empty Python file to the folder python_work, and name it hello_world.py. The extension .py tells Geany that the file contains a Python program; it also lets Geany know how to run the program and highlights the code in it in a useful way.
After saving the file, enter the following line of code in it:

print(“Hello Python world!”)

If you can execute the command python in the system, you don't need to configure Geany, so you can skip the next part and go directly to the "Run Hello World Program" part. If you must specify the path when starting the Python interpreter, such as C:\Python35\python, please follow the instructions below to configure Geany.

  • Five. Place Geany

To configure Geany, select the menu Build Set Build Commands; you will see the words Compile and Execute, which have a command next to them. By default, the beginning of the compile command and the execution command is python, but Geany does not know where the command python is stored in the system, so you need to add the path you use in the terminal session.
To this end, add the drive and folder where the command python is located in the compile command and the execution command. The compilation command should be similar to the following:

C:\Python35\python -m py_compile “%f”

In your system, the path may be slightly different, but please make sure that the spaces and capitalization are the same as those shown here.
The execution command should be similar to the following:

C: \ Python35 \ python “% f”

Similarly, when specifying the execution command, make sure that the spaces and capitalization are the same as those shown here. Figure 1-3 shows how to configure these commands in Geany.
[illustration]

Figure 1-3 After configuring Geany in Windows to use Python 3
to set these commands correctly, click the OK button.

  • 6. Run the Hello World program

You should be able to run the program successfully now. Please run the program hello_world.py; to do this, select the menu Build Execute, click the Execute icon (two gears) or press F5. A terminal window will pop up with the following output:

Hello Python world!
------------------
(program exited with code: 0)
Press return to continue

If you don't see this output, please check every character you type. Did you capitalize the first letter of print? Did you miss the quotation marks or brackets? Programming languages ​​have very strict requirements on grammar. As long as you do not strictly follow the grammar, errors will occur. If the code is correct, the program will not run correctly, please refer to the next section.

1.3 Solve installation problems

If you follow the previous steps, you should be able to successfully set up a programming environment. But if you still cannot run the program hello_world.py, you can try the following solutions.

  • When there is a serious error in the program, Python will display a traceback. Python will study the file carefully, trying to find the problem. Traceback may provide clues to let you know what is causing the program to fail to run.

  • Leave the computer, rest for a while, and try again. Don't forget, in programming, grammar is very important. Even one missing colon, mismatched quotation marks, or mismatched parentheses may cause the program to fail to run correctly. Please read the related content in this chapter again, review your work again, and see if you can find the error.

  • Overturn and start over. You may not need to rebuild everything, but deleting the file hello_world.py and recreating it may be a reasonable choice.

  • Ask someone to repeat the steps in this chapter on your computer or another computer, and observe carefully. You may have missed a small step, and someone else just missed it.

  • Please help from someone who understands Python. When you have such an idea, you may find that some people you know use Python.

  • The installation instructions for this chapter are on the home page of this book: http://www.ituring.com.cn/book/1861 . For you, the online version may be more suitable.

  • Go online for help. Appendix C provides many online resources, such as forums or online chat sites. You can go to these places and ask someone who has solved the problem you face to provide a solution.

Don't worry about this disturbing experienced programmers. Every programmer has encountered problems, and most programmers will be happy to help you set up the system correctly. As long as you can clearly state what you are going to do, what methods have been tried, and the results, it is likely that someone can help you. As pointed out in the preface, the Python community is very friendly to beginners.
Any modern computer can run Python. If you encounter difficulties, please find a way to ask for help. The early problems may be frustrating, but it is well worth your time to solve them. After being able to run hello_world.py, you can start learning Python, and programming will be more interesting and enjoyable.

1.4 Run Python programs from the terminal

Most programs you write will run directly in a text editor, but sometimes it is useful to run the program from a terminal. For example, you may want to run an existing program directly.
You can do this on any system with Python installed, provided you know how to enter the directory where the program files are located. To try this, make sure you have stored the file hello_world.py in the python_work folder on your desktop.

1.4.1 Run Python programs from the terminal in Linux and OS X

In Linux and OS X systems, the way to run Python programs from the terminal is the same. In a terminal session, you can use the terminal command cd (for change directory) to navigate in the file system. The command ls (short for list) displays all unhidden files in the current directory.
To run the program hello_world.py, please open a new terminal window and execute the following command:

~>cd Desktop/python_work/ ❶
~/Desktop/python_work>ls ❷
hello_world.py
~/Desktop/python_work>python hello_world.py ❸
Hello Python world!

The command cd is used here to switch to the folder Desktop/python_work (see ❶). Next, use the command ls to confirm that this folder contains the file hello_world.py (see ❷). Finally, use the command python hello_world.py to run this file (see ❸).
It's that simple. To run a Python program, just use the command python (or python3).

1.4.2 Run Python program from terminal in Windows system

In the command window, to navigate in the file system, you can use the terminal command cd; to list all files in the current directory, you can use the command dir (for directory, directory).
To run the program hello_world.py, please open a new terminal window and execute the following command:

C:\>cd Desktop\python_work ❶
C:\Desktop\python_work>dir ❷
hello_world.py
C:\Desktop\python_work>python hello_world.py ❸
Hello Python world!

The command cd is used here to switch to the folder Desktop\python_work (see ❶). Next, use the command dir to confirm that this folder contains the file hello_world.py (see ❷). Finally, use the command python hello_world.py to run this file (see ❸).
If you have not configured the system to use the simple command python, you may need to specify the path of this command:

C:\$cd Desktop\python_work
C:\Desktop\python_work$dir
hello_world.py
C:\Desktop\python_work$C:\Python35\python hello_world.py
Hello Python world!

Most programs can be run directly from the editor, but when the problem to be solved is more complicated, the program you write may need to be run from the terminal.

1.5 Summary

In this chapter, you have a general understanding of Python and installed Python on your system. You also installed a text editor to simplify the writing of Python code. You learned how to run Python code snippets in a terminal session and ran the first real program-hello_world.py. You also have a general idea of ​​how to solve installation problems.
In the next chapter, you will learn how to use various data and variables in Python programs.

Guess you like

Origin blog.csdn.net/weixin_43510203/article/details/112176814