Follow 👆 the public account and reply with "python" to receive a zero-based tutorial! Source from the internet, please delete if infringing
Data analysis, scientific drawing, web scraping… coding basics are essential skills for learning and research in our era.
【Tutorial Retrieval method at the end of the article!!】
Are you troubled by scientific images and data processing?
VS Code or PyCharm? Are you confused about which Python editor to use? How should you install and use it?
This issue brings you an introduction to getting started with Python~
Table of Contents:
1. What is Python?
2. Python application areas
3. Basic configuration of Python
– Installation
– Interactive window and script files
– VS Code & PyCharm
4. Getting started with Python
– Virtual environments and packages
– Basic syntax
– Generative artificial intelligence
#1
What is Python?
Python is a elegant and robust programming language designed by Guido van Rossum at the Centrum Wiskunde & Informatica in the early 1990s. It inherits the power and universality of traditional compiled languages while also drawing on the usability of scripting and interpreted languages.
Python is designed to be “in line with the brain’s thinking habits”, adopting a minimalist design philosophy with a unified standard interaction mode. This makes Python easy to learn, understand, and remember. The philosophy of Python developers is “There should be one—and preferably only one—obvious way to do it.”


Advantages of Python
● Simple and easy to understand: Python is a language that embodies the philosophy of simplicity, with a syntax design that has strong readability, a clear and consistent style, and forced indentation, allowing users to focus on writing code logic without worrying about low-level details like memory.
● Fast development speed: The simple syntax, dynamic typing, no need for compilation, and rich library support mean that Python often requires only dozens of lines of code to achieve functionality that would require hundreds of lines of C code.
●Interpreted language: Does not need to be compiled into binary code, eliminating the compilation step during development.
●Interactive language: You can directly input and execute code at the terminal prompt >>>.
●Object-oriented: Supports both “procedural” and “object-oriented” programming. Functions, modules, numbers, and strings are all objects. It fully supports inheritance, overloading, derivation, and multiple inheritance, which enhances the reusability of source code.
●Expandable and embeddable: The basic code library covers areas such as regular expressions, networking, multithreading, GUI, and database programming. In addition to built-in libraries, Python also has a large number of third-party libraries available for direct use, such as Django, TurboGears, and Pylons in the web domain and data analysis.
● Cross-platform: The portability of C allows Python to run on any platform with an ANSI C compiler, including Linux, Windows, MacOS, and Unix.
● Beginner language: Supports a wide range of application development, from word processing to browser architecture and games.

Disadvantages of Python
● Slower execution speed: As an interpreted language, Python needs to be translated line by line into machine code that the CPU can understand, while C programs are compiled into machine code that the CPU can execute before running, making Python slower than C/C++ programs. However, according to the Pareto principle, most programs do not have high speed requirements. For cases that require high execution speed, JIT technology can be used, or the part of the program can be rewritten in C/C++.
● Code cannot be encrypted: Releasing a Python program is essentially equivalent to releasing the source code, while C language releases compiled machine code, and it is impossible to fully reverse-engineer C code from machine code.
#2
Python Application Areas
Due to the simplicity, readability, and extensibility of Python, there is an increasing number of research institutions abroad using Python for scientific computing, and some well-known universities have adopted Python to teach programming courses. For example, Carnegie Mellon University’s introductory programming and MIT’s introduction to computer science and programming both use Python as the teaching language.
In scientific research, the application of Python is very extensive. Many open-source scientific computing software packages provide Python calling interfaces, such as the well-known computer vision library OpenCV, 3D visualization library VTK, and medical image processing library ITK. There are even more Python-specific scientific computing extension libraries, such as three classic scientific computing extension libraries: NumPy, SciPy, and matplotlib, which provide fast array processing, numerical computation, and plotting capabilities for Python. Therefore, the development environment formed by the Python language and its many extension libraries is very suitable for engineers and researchers to process experimental data, create charts, and even develop scientific computing applications.

#3
Basic Configuration of Python
3.1 Installing Python
Currently, there are two versions of Python: 2.x and 3.x. These two versions are not compatible. As version 3.x becomes increasingly popular, our tutorial will be based on the latest Python 3.12 version. Please ensure that the Python version installed on your computer is the latest 3.12.x.
Installing Python on Mac
If you are using a Mac with OS X>=10.9, the system comes with Python version 2.7. To install the latest Python 3.12, there are two methods:
– Method 1: Download the Python 3.12 installer from the official Python website, double-click to run and install;
– Method 2: If you have Homebrew installed, you can directly install it using the command brew install python3
.
Installing Python on Windows
Similarly, download the Python 3.12 installer from the official Python website. Remember to check Add To Path during installation to save the installation path as a system environment variable.
What is an Environment Variable?
You can refer to this article for the basic concept of environment variables. If you forgot to add the path of Python to the environment variable during installation, you can try to add it to Path manually.

3.2 Interactive Window and Script Files
Based on the characteristics of interpreted languages, Python code can be executed in two ways: interactive window and script files.
● Interactive window: Enter python
in the command line to enter the interactive window, where you can input one line of code and Python will execute it immediately and return the result. To exit, press Ctrl+D or execute exit()
(Windows users should use Ctrl+Z).

● Script: The classic way to run is python
, and Python will execute the entire script according to the order of statements from beginning to end. For various engineering projects, we naturally choose to store code in script files for convenience in making calls. For beginners, we can try using the interactive window to get started. In subsequent sections with code, if there is a prompt >>>, it indicates this is an interactive window, while code with >>> is the code, and the rest is the output of the executed code.

So, where should we write and debug script files? Next, we introduce the two most commonly used Python integrated development environments.
3.3 Python IDE: VS Code
Visual Studio Code (VSCode) is a free and open-source code editor developed by Microsoft. It supports multiple programming languages, including Python. VSCode is favored by developers for its simple interface, powerful features, and excellent performance. You can download it from the VS Code official website.
VS Code Installation and Basic Usage
Open VS Code, complete the beginner tutorial, and click the Extensions button on the left toolbar to install the Python extension, which allows you to program in Python within VS Code. Of course, there are many very useful plugins in VS Code that you can refer to in the xx column.

Click open folder to open the folder where you want to store your code. Here, we use a newly created empty folder named xiuzhongkexie as a demonstration. After opening, you will see that the directory of this folder is empty, and you can right-click to select new file to create a Python file ending with .py. Next, you can write Python code in this file.


3.4 Python IDE: PyCharm
PyCharm is a very useful Python IDE developed by JetBrains, equipped with a complete set of tools to help users improve their efficiency when developing with Python, supporting professional web development under the Django framework.
Compared to VS Code, PyCharm offers more convenient environment management, does not require you to build an IDE yourself to use it, and installing plugins and running extensions is relatively convenient, making it very user-friendly for beginners, and it has strong advantages in large project file development; however, it occupies more memory.
PyCharm Installation and Basic Usage
!!! From April 11, 2024, all faculty and students at Tsinghua University can obtain the professional version of JetBrains software through campus genuine software service.
For detailed tutorials, refer to:
Network management notification | JetBrains series software is coming!!!

During the installation process of PyCharm, it is recommended to modify the installation path, and try not to place it on the C drive to save memory. Other settings are as follows; remember to check Add “bin” folder to the PATH. After installation, you need to restart the system (Reboot). If inconvenient, you can choose to restart manually later.

After installation, you can perform the following basic settings:
●Interpreter configuration: Executing Python code requires an interpreter, which is the version of Python used.
You can set this in the upper left corner under File -> settings of the project name -> Project Interpreter, as shown below.

● Default encoding for Python files: You can select the required character encoding in the upper left corner under File -> Editor -> File Encodings -> Global Encoding and Project Encoding, usually using UTF-8 encoding.

After completing the basic settings, you can create a Python project to write programs~
● Create a project: Click on the upper left corner File–> New Project –> create a new project, right-click on the project name –> new –> python file –> enter hello to create a hello.py file.

●Run code:: Click the small triangle in the upper right corner to run the written code and view the running results in the terminal below.

#4
Getting Started with Python
4.1 Virtual Environments and Packages
Before discussing virtual environments, let’s first introduce what a package is.
A package is actually Python code that has been written and published by someone else for everyone to use. When writing Python, we often need to import a series of packages to avoid writing a lot of code ourselves (for example, if you need to calculate an average, you can import a package that has the averaging functionality) such as import xxx
, from xxx import xx
, all of which import packages.

In Python development, we often need to use various packages to accomplish different tasks. However, packages have versions; when an author releases a package, if they find bugs or want to update features, they will continue to iterate versions. We may need different versions of the same package for different projects. For example, project A requires package a1.0, while project B requires package a2.0, which leads to a problem: if we have already installed package a1.0, project B may not work properly because multiple versions of the same package cannot exist simultaneously!
To solve this problem, we can create an independent Python runtime environment for each project, called a virtual environment. In a virtual environment, we can install specific versions of libraries without affecting other projects. The specific steps are as follows:
Creating and Setting Up a Virtual Environment
● Enter the directory: Open the command line and enter the directory where you want to create the virtual environment. If the directory displayed here is not the one where you want to create the virtual environment, please open the desired directory from VSCode first, then open the terminal.

●Creating a virtual environment:: Execute the following command in the command line to create a virtual environment named myenv: python -m venv xiuzhong
. Here, “xiuzhong” can be any name you want to give your virtual environment. After creation, you will see a folder named xiuzhong in the current directory, which contains the files for the virtual environment.

●Activating the virtual environment: After creating the virtual environment, we need to activate it to install and use packages within it. The activation method varies by operating system:
On Windows: xiuzhong\Scripts\activate
On MacOS: source xiuzhong/bin/activate
After activation, you will find that a prefix (xiuzhong) has been added to the command line prompt, indicating that you are operating within the virtual environment.

The name of this virtual environment will also appear in the lower right corner of VS Code:

If the newly created virtual environment does not appear, click on it, and a prompt window will appear at the top. Click the circle in the top right corner of the prompt window to refresh, and you will find the virtual environment you just created.

●Installing packages:: After activating the virtual environment, we can use the pip command to install the required packages within it, for example:
pip install pandas
If a bunch of output appears, it means the installation was successful.

#Mirror source configuration: If the installation speed is too slow, it is because many of these packages are from abroad. You can add the following after the command pip install pandas -i
https://pypi.tuna.tsinghua.edu.cn/simple, which means to download from Tsinghua’s mirror source.
# Bug: If you encounter the following error when running the code later (“No module named xxx”), it usually means that you did not install this package correctly. You need to search for how to install this xxx (usually pip install xxx, occasionally there are exceptions like the cv2 package which requires pip install opencv-python to install).

●Exiting the environment:: After completing work within the virtual environment, we can use the following command to exit:
deactivate
Once the prefix xiuzhong disappears from the command line prompt, it indicates that you have exited the virtual environment.
4.2 Basic Syntax
●Input and Output: Input and output in Python are achieved through built-in functions.
– Input: input() function: This function allows the program to pause and wait for user input. The user input will be returned as a string.
– Output: print() function: This function is used to output information to the console. You can output strings, numbers, variables, and more complex data structures.


– File Input and Output: To read content from a file or write content to a file, you can use the open()
function to open the file, then use the methods of the file object to read or write.

● Variable Creation: In Python, you can create a variable by directly assigning a value to it without declaring a data type in advance. Python is a dynamically typed language, automatically inferring the data type during assignment.
Variable Naming Rules:
• Variable names must start with a letter (a-z, A-Z) or an underscore (_).
• Variable names cannot start with a number.
• Variable names can only contain letters, numbers, and underscores (a-z, A-Z, 0-9, _).
• Variable names are case-sensitive; for example, myVariable and myvariable are two different variables.
• Variable names should be descriptive; for example, use age instead of a, and user_name instead of un.
• Reserved words (also known as keywords) are words that have specific meanings in Python, such as: if, for, class, def, return, etc., and cannot be used as variable names, function names, or any other identifiers. You can use the keyword module to view all Python keywords.
●Indentation:: In Python, indentation is part of the syntax used to define the beginning and end of code blocks. According to Python’s syntax, each level of indentation uses 4 spaces (or Tab).

●Comments: Single-line comments start with “ #”. Python does not have a dedicated syntax for multi-line comments, but it typically uses three consecutive single quotes (”’) or double quotes (“””) to create string literals that are treated as multi-line comments, although they are actually multi-line strings. If these strings are not assigned to a variable or used in an expression, the interpreter will ignore them, so they can be used as multi-line comments.

●Data Types: Mainly includes three categories: numbers (integers, floating-point numbers), strings, and boolean values (True or False).

● Operators:
– Arithmetic operators: +, -, *, /, …
– Assignment operators: –=, +=, -=, …
– Comparison operators: –>=, <=, ==, …
– Logical operators: and, or, not
– Identity operators: is, is not
– Membership operators: in, not in

● Data Structures: Sequential structure, loop structure, branch structure.
– Sequential structure: Executes in order from top to bottom.
– Loop structure: Allows code to be executed repeatedly, including for loops (used to iterate over iterable objects such as lists, tuples, dictionaries, sets, strings) and while loops (executing code blocks repeatedly while a specified condition is met).

– Branch structure: Allows the program to choose different execution paths based on certain conditions, implemented through if, elif, and else keywords.

●Creating Functions: Typically defined using the def keyword, followed by the function name and parameter list, then a colon, followed by the function body. If the function needs to return a value, you can use the return statement.

– A lambda function is an anonymous function defined using the lambda keyword, which does not need to have a function name. It is typically used to define simple, one-time, unnamed small functions and is often used when a function needs to be passed as a parameter.

For the complete tutorial, you can refer to the “Rookie Tutorial” and CSDN as supplements:
Python Basic Syntax | Rookie Tutorial
CSDN – Professional Developer Community
4.3 Programming Assistant – Generative Artificial Intelligence
Q1: What is Generative Artificial Intelligence?
Generative artificial intelligence is an AI technology that can generate new content (such as text, images, audio, etc.). Unlike traditional discriminative AI, generative AI can not only recognize and classify existing content but also create new content based on learned patterns. In the programming field, generative AI can automatically generate code snippets that meet requirements based on given instructions or context, and optimize and fix existing code. This capability stems from generative AI’s training on massive code data, enabling it to understand the syntax, semantics, and best practices of programming languages.
Generative AI has a wide range of applications in programming, including:
– Code auto-completion: Predicts and recommends the next possible lines of code based on context.
– Code generation: Automatically generates corresponding code implementations based on natural language descriptions or framework structures.
– Code optimization: Automatically detects and optimizes performance bottlenecks, memory leaks, and other issues in the code.
– Code debugging: Recommends possible fixes based on error messages and code context.
– Code documentation generation: Automatically generates documentation comments and usage instructions for functions, classes, and modules.
Generative AI can significantly improve developers’ work efficiency, reduce repetitive coding tasks, and help beginners quickly master programming skills.
This tutorial uses ZhiPu QingYan as a programming assistant. ZhiPu QingYan is one of the strongest generative AI models developed by Tsinghua’s team.
Log in to the ZhiPu QingYan web version and complete the registration.
Q2: How to ask about code?
Ask ZhiPu QingYan about the meaning or usage of a piece of code as follows:


Q3: How to generate code?
Generate code based on your requirements. Let’s take an example from Teacher Dong Xin’s assignment in “Environmental Data Processing and Mathematical Models”:

ZhiPu QingYan easily completed the task and also explained the code in detail:

Q4: How to debug code?
Also using the code from the previous assignment, if we want to print the sampling results but encounter an issue, we can also seek help from ZhiPu QingYan:

After debugging, the sampling results are successfully printed:

In the process of learning Python, large language models can indeed provide significant help. They can automatically generate Python code based on your requirements, help you analyze and fix errors, optimize code performance, and provide design suggestions. These intelligent aids can significantly improve learning efficiency and accelerate the process of mastering Python programming skills.
However, we must also recognize that large language models are not omnipotent; they cannot completely replace human programming and problem-solving. The code generated by large language models may contain errors or be unsuitable, and we still need to review and test it. At the same time, for some complex, specialized, or innovative programming tasks, large language models may not provide satisfactory solutions, requiring us to exercise our creativity and expertise.
Therefore, in the process of learning Python, we should reasonably utilize the auxiliary functions of large language models as tools and assistants for learning, rather than fully relying on them. We still need to systematically learn the syntax, semantics, libraries, and tools of Python, understand common algorithms and design patterns, and accumulate practical programming experience. Only by establishing a solid programming foundation can we better apply large language models and analyze, improve, and innovate based on their suggestions.
In summary, large language models provide intelligent assistants for Python beginners, guiding and accelerating the learning process. However, we should not rely on them entirely; instead, we should combine them with systematic learning and hands-on practice to truly grasp the essence of Python programming and become a qualified Python developer. (This paragraph was generated by ZhiPu QingYan)
Retrieval Method:
-
Like + See Again
-
Reply “python” in the public account
Get the latest zero-based learning materials for Python in 2024, reply in the background:Python