Python Crash Course
About Python
Python is a widely used interpreted language worldwide. It provides efficient high-level data structures and supports simple and effective object-oriented programming, also suitable for algorithm competitions.
Advantages of Python
- Python is an interpreted language: Python does not require compilation and linking, which can reduce operational steps to some extent.
- Python is an interactive language: The Python interpreter implements interactive operations, allowing direct input and execution of commands in the terminal.
- Python is easy to learn and use: Python provides a large number of data structures and also supports developing large programs.
- Python has strong compatibility: Python supports Windows, macOS, and Unix operating systems simultaneously.
- Python is highly practical: From simple input/output to scientific computing and even large WEB applications, suitable Python programs can be written.
- Python programs are concise and readable: Python code is usually shorter than code in other languages that implement the same functionality.
- Python supports extension: Python can interface with C programs (i.e., CPython), supporting linking the Python interpreter with applications developed in C, and using Python to extend and control the application.
Notes on Learning Python
- The main Python versions currently in use are Python 3.7 and above. Python 2 and Python 3.6 and earlier Python 3 versions are no longer supported, but are still used by some legacy systems and code. This article will introduce newer versions of Python. If you encounter Python 2 code, you can try the
2to3program to convert Python 2 code to Python 3 code. - Python's design philosophy and syntax structure differ significantly from some other languages, hiding many low-level details, thus presenting a practical and elegant style.
- Python is a highly dynamic interpreted language, so its program execution speed is relatively slow, especially when using its built-in
forloop statements. When using Python, try to use built-in functions likefilter,map, or means like list comprehensions to improve program performance.
Environment Setup
Refer to Python 3. Alternatively:
-
Windows: You can also get Python for free and quickly from the Microsoft Store.
-
macOS/Linux: Typically, most Linux distributions come with Python pre-installed. If you only intend to learn Python syntax without other development needs, there is no need to install Python separately.
Note
On some systems where Python is installed by default (i.e., using a package manager), such as Unix systems, you should run
python3in the terminal to open the Python 3 interpreter.[^ref1]
Additionally, you can use tools like venv, conda, Nix, etc., to manage the Python toolchain and Python packages, creating isolated virtual environments to avoid dependency issues.
As an interpreted language, Python's execution method differs from C++, and this difference is often not reflected when programming with an IDE, so it's necessary to emphasize the different ways of running programs.
When you type python3 in the command line or just open IDLE, you actually enter an interactive programming environment, also known as a "REPL" ("Read-Eval-Print Loop"). Beginners can input statements here and see results immediately, making it extremely easy to verify some syntax. We will also use this form extensively later.
However, to write complete programs, it's better to create a new text file (usually with the .py suffix) and then execute python3 filename.py in the command line to run the code and see the results.
Python Versions Provided by Some Platforms
| System Name/Version | Python Version |
|---|---|
| Noi Linux 2.0 | 3.8.0, Include requests |
| Luogu Judge | 3.11.5, NumPy 1.25.2 |
| Hydro-based OJ | 3.8.0+ Include NumPy |
| Ubuntu 22.04 (built-in) | 3.10.4 |
| Microsoft Store | Latest stable version |
Note
This table is valid as of the writing of this article (2025/01/15). It is recommended to verify with the relevant platforms.
Currently, domestic mirror caches for source code are mainly Beijing Jiaotong University Free and Open Source Software Mirror and Huawei Open Source Mirror. You can try downloading Python installation files from there.
Installing Third-Party Libraries with pip
Python's vitality largely comes from its rich third-party libraries. "Calling libraries" is a common practice when writing practical programs, and pip is the preferred program for installing third-party libraries. Since Python 3.4, it has been included by default in the Python binary installer.
Third-party libraries in pip are mainly stored on the Python Package Index (PyPI). Users can also specify other third-party library hosting platforms. Usage methods can refer to pypi mirror usage help - Tsinghua University Open Source Software Mirror and other usage guides. You can get more PyPI mirror sources on MirrorZ.
Installing a package using Tsinghua University Open Source Mirror
1 | |
Basic Syntax
Python's syntax is concise and easy to understand, with many official and third-party documents and tutorials. Here, we only introduce some language features that are more practical for OIers. You can learn more about Python tutorials on pages like Python Documentation and Python Wiki.
Comments
Adding comments does not affect the running of the code, but it can make the code easier to understand and use.
1 2 3 4 5 6 7 | |
Adding comments does not affect the code. We encourage adding comments to make the code more understandable and usable.
Basic Data Types
Everything is an Object
In Python, you don't need to declare variable names and their types in advance; you can create variables of various types by direct assignment:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
But this doesn't mean Python has no concept of types. In fact, the interpreter automatically infers variable types based on assignment or operations. You can use the built-in function type() to view the types of these variables:
1 2 3 4 5 6 7 8 | |
What are built-in functions?
In C/C++, many commonly used functions are scattered across different header files, but Python's interpreter has many practical and general functions built-in. You can use them directly without paying attention to their existence, but this also brings a small problem: the names of these built-in functions are mostly common words. You need to avoid giving your variables the same names, otherwise strange results may occur.
As we have seen, Python has built-in integer, float, string, and boolean types, which can be analogized to int, float, string, and bool in C++. But there are some obvious differences, such as no char character type and no double type (but float actually corresponds to double precision in C). If more precise floating-point operations are needed, you can use the decimal module in the standard library. If complex numbers are needed, Python also has a built-in complex type (which also means it's best not to name a variable complex).
You can see that these types all start with class, which is a key difference between Python and C++. All data in a Python program is represented by objects or relationships between objects. Functions are objects, and types themselves are also objects:
1 2 3 4 5 6 | |
You might find these concepts difficult to understand and seemingly useless at the moment, so we won't go deeper for now. In later examples, you might gradually realize that Python objects provide powerful methods. When programming, we should prioritize operations around objects rather than processes, which will make our code more compact and clear.
Numeric Operations
Some say you can use the Python installed on your system as a multi-purpose calculator, which is true.
In interactive mode, you can input an expression after the prompt >>>, using operators +, -, *, /, % to perform operations on numbers, just like in most other languages (such as C++). You can also use () for grouping that follows associativity. Readers can experiment on their own. Here we only show parts that differ significantly from C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
From the above practice, you can find that division (/) always returns a float type (in Python 2, it returns an integer). If you want integer or floor division results, you can use integer division (//). Similarly, you can use modulo (%) to calculate remainders as in C++. The form of scientific notation is also the same.
Specifically, Python uses ** for exponentiation and provides an efficient implementation of fast exponentiation through the built-in pow(a, b, mod).
1 2 3 4 5 6 7 8 9 | |
Data Type Judgment
For a variable, you can use type(object) to return the variable's type. For example, type(8) and type('a') are <class 'int'> and <class 'str'> respectively.
Basic Input/Output
Input and output in Python are mainly done through the built-in functions input() and print(). The usage of print() is very intuitive:
1 2 3 4 5 6 7 8 9 | |
The behavior of input() is similar to getline() in C++, reading an entire line as a string, with no newline at the end.
1 2 3 | |
Strings
Python 3 provides a powerful Unicode-based string type. Its usage is similar to string in C++. Some concepts like escape characters are also相通. Besides concatenation with + and index access, it additionally supports multiplication * to repeat strings and the in operator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | |
Python supports multiple compound data types that combine different values. The most commonly used list type is a comma-separated set of values enclosed in square brackets. For example, [1, 2, 3] and ['a','b','c'] are both lists.
Besides indexing, strings also support slicing, which is ingeniously designed with the format s[left_inclusive_index:right_exclusive_index:step]:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
In the latest Python 3 versions, strings are encoded in Unicode, meaning Python strings support multiple languages.[^ref2] In Python, you can use the built-in function ord() to convert a Unicode character to its corresponding Unicode code point. The reverse conversion uses the built-in function chr(). In C/C++, the char type can also be converted to and from its corresponding ASCII code.
If you want to convert a number to its corresponding string, you can use the built-in function str(). Conversely, you can use int() and float(). You can think of this as type casting in C/C++, but the parentheses are not placed on the type but are part of the function enclosing the parameters.
Python's string type provides many powerful methods, including calculating the index and count of a character, converting case, etc. We won't list them all here. It is strongly recommended to check the official documentation to familiarize yourself with common methods. When performing string operations, you should first consider using these methods rather than reinventing the wheel.
Creating Arrays
Students coming from C++ might be confused about how to create arrays in Python. Here we introduce the syntax for creating "arrays" in Python. It should be emphasized that what we are introducing are actually several sequence types, which are fundamentally different from C arrays and closer to vector in C++.
Using list
Lists (list) are probably the most commonly used and powerful sequence type in Python. Lists can store elements of any type, including nested lists, which fits the definition of "generalized lists" in data structures. Please do not confuse them with the bidirectional linked list list in C++ STL. Therefore, this article will use "list" instead of list to avoid confusion.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | |
The above examples show the similarities between lists and vector. Operations commonly used in vector generally have corresponding methods in lists. However, some methods like len(), sorted() appear as built-in functions, while functions from STL algorithms like find(), count(), max_element(), sort(), reverse() become object methods in Python. Be careful to distinguish them. For more methods, see the official documentation's More on Lists. Below we demonstrate some powerful features of lists as Python's basic sequence type:
Python supports multiple compound data types that combine different values. The most commonly used list type is a comma-separated set of values enclosed in square brackets. For example, [1, 2, 3] and ['a','b','c'] are both lists.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | |
The above examples show some common operations on lists as sequences. Many operations like slicing are shared with strings, but strings are "immutable sequences" while lists are "mutable sequences", so lists can be flexibly modified via slicing. In C/C++, we often process character arrays through loops. Below we show how to use list comprehensions to convert between strings and lists:
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
Below are some more common scenarios in OI, such as two-dimensional "arrays":
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | |
Actually, there is an important fact: assignment in Python only passes references rather than creating new values. You can create variables of different types and assign them to new variables, verifying that their identity values are the same. It's just that until now we have only introduced lists as a mutable type. When assigning new values to immutable types like numbers and strings, new objects are actually created, so the two variables before and after do not interfere. But lists are mutable types, so when we modify an element of one list, the other list, pointing to the same object, is also modified. Creating 2D arrays is similar. Using multiplication to create a 2D list is equivalent to repeating the one-dimensional list [0]*3 three times, so operations involving one list affect the other two. Worse, when assigning a 2D list to other variables, even using slicing to copy is only a "shallow copy"; the elements still point to the same objects. To solve this, you need to use deepcopy from the standard library, or avoid assigning entire 2D lists. Fortunately, it's relatively simple to avoid creating duplicate lists when creating 2D lists by using list comprehensions:
1 2 3 4 5 6 7 8 9 | |
We introduced list comprehensions before explaining loop usage because Python is a highly dynamic interpreted language, so its program execution has significant overhead. Especially for loops run extremely slowly in Python. Therefore, to achieve high performance in Python, try to use list comprehensions or built-in functions like filter, map to operate on entire sequences directly to avoid loops, though this still depends on the specific problem.
Using NumPy
What is NumPy
NumPy is a famous Python scientific computing library providing high-performance numerical and matrix operations. When testing algorithm prototypes, NumPy can be used to avoid handwriting sorting, finding maxima, etc. NumPy's core data structure is ndarray, i.e., n-dimensional array, which is stored contiguously in memory and has fixed length. Additionally, NumPy's core is written in C, so it's highly efficient. However, note that it's not part of the standard library; you can install it with pip install numpy, but it's not guaranteed to be available in OI contest environments (see the Python Versions section at the beginning).
The following code introduces how to use NumPy to create multi-dimensional arrays and access them.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | |
Using array
array is an efficient numerical array provided by Python's standard library, capable of compactly representing arrays of basic type values, but it does not support nested arrays and is rarely seen in use. It's mentioned here just in passing.
Unless otherwise specified, "array" in the following text generally refers to "list".
Input/Output
Input and output in Python are mainly done through the built-in functions input() and print(). They have been introduced earlier; here we cover advanced usage.
Formatted Output
Algorithm competitions usually only involve basic numerical and string output, for which print() is mostly sufficient. Only when dealing with floating-point precision is formatted string output needed. There are three methods for formatting. The first and oldest is using the printf()-style % operator; another is using the format function; the third is f-string added in Python 3.6, which is the most concise but not guaranteed to be supported in contest environments due to Python version. Detailed explanations can be found on this webpage. Although using the format() method is recommended, to get an experience close to C, we only demonstrate the old method similar to printf():
1 2 3 4 | |
split() Function
The input() function behaves similarly to getline() in C++, reading an entire line as a string with no newline at the end. However, in algorithm competitions, common input forms involve multiple values per line, so you need to use the string's split() method combined with list comprehensions to get a list storing numerical types. Below is an example of inputting n numbers to calculate the average, demonstrating how to get an "array" from inputting n numbers:
```pycon
s = input('Please enter a string of numbers: '); s # When debugging, you can pass a string to input() as a prompt Please enter a string of numbers: 1 2 3 4 5 6 '1 2 3 4 5 6' a = s.split(); a ['1', '2', '3', '4', '5', '6'] a = [int(x) for x in a]; a [1, 2, 3, 4, 5,
本页面最近更新:,更新历史
发现错误?想一起完善? 在 GitHub 上编辑此页!
本页面贡献者:OI-wiki
本页面的全部内容在 CC BY-SA 4.0 和 SATA 协议之条款下提供,附加条款亦可能应用