Skip to content

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 2to3 program 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 for loop statements. When using Python, try to use built-in functions like filter, 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 python3 in 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
pip install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple <some-package>

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
# Lines starting with the # character are single-line comments

"""
Multi-line strings are enclosed with triple quotes
(three single quotes or three double quotes)
but are also commonly used for comments
"""

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
>>> x = -3  # No semicolon needed at the end of a statement
>>> x
-3
>>> f = 3.1415926535897932384626; f  # You can add a semicolon if you really want to, saving a line here
3.141592653589793
>>> s1 = "O"
>>> s1  # In Python, double quotes and single quotes serve the same purpose
'O'
>>> b = 'A' == 65  # 'A' and 65 are not the same data type, so they are not equal
>>> b  # True, False both start with capital letters
False
>>> True + 1 == 2 and not False != 0  # Python expressions mostly use words, but symbols are also supported
True

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
>>> type(x)
<class 'int'>
>>> type(f)
<class 'float'>
>>> type(s1)  # Please note, do not name a string 'str', otherwise the str object will be overwritten
<class 'str'>
>>> type(b)
<class 'bool'>

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
>>> type(int)
<class 'type'>
>>> type(pow)  # Built-in function for exponentiation, introduced later
<class 'builtin_function_or_method'>
>>> type(type)  # type() is also a built-in function, but somewhat special; interested readers can look it up
<class 'type'>

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
>>> 5.0 * 6  # Operations with floats result in floats
30.0
>>> 15 / 3  # Unlike C/C++, division always returns a float type
5.0
>>> 5 / 100000  # Too many digits, result shown in scientific notation
5e-05
>>> 5 // 3 # Using integer division (floor division) rounds down, outputting an integer type
1
>>> -5 // 3 # Follows the floor division principle, note this is different from C/C++
-2
>>> 5 % 3 # Modulo
2
>>> -5 % 3 # Negative modulo results are always non-negative, which is also different from C/C++, but both satisfy (a//b)*b+(a%b)==a
1
>>> x = abs(-1e4)  # Built-in function for absolute value
>>> x += 1  # No increment/decrement operators
>>> x  # Scientific notation defaults to float
10001.0

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
>>> 3 ** 4 # Exponentiation
81
>>> 2 ** 512
13407807929942597099574024998205846127479365820592393377723561443721764030073546976801874298166903427690031858186486050853753882811946569946433649006084096
>>> pow(2, 512, int(1e4)) # Fast implementation of 2**512 % 10000, 1e4 is float so convert to int
4096
>>> 2048 ** 2048 # Try big integers in IDLE?
>>> 0.1 + 0.1 + 0.1 - 0.3 == 0.  # Like C/C++, note that floats cannot be directly compared for equality
False

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
>>> a = [1,2,3]; print(a[-1])  # Prints with a newline at the end by default
3
>>> print(ans[0], ans[1])  # Can output any number of variables, separated by spaces by default
1 2
>>> print(a[0], a[1], end='')  # Set end='' to not newline at the end
1 2>>>
>>> print(a[0], a[1], sep=', ')  # Set sep=', ' to change the separator style
1, 2
>>> print(str(a[0]) + ', ' + str(a[1]))  # Same output as above, but manually concatenated into one string

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
>>> 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'

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
>>> s1 = "O"  # Both single and double quotes can enclose strings, sometimes saving escape characters
>>> s1 += 'I-Wiki'  # For consistency with C++, it is recommended to use double quotes
>>> 'OI' in s1  # Convenient substring detection
True
>>> len(s1)  # Similar to s.length() in C++, but more general
7
>>> s2 = """ Thank you for reading
... Welcome to contribute!
"""   # Strings using triple quotes can span multiple lines
>>> s1 + s2
'OI-Wiki Thank you for reading\nWelcome to contribute!'
>>> print(s1 + s2)  # Here the print() function is used to print the string
OI-Wiki Thank you for reading
Welcome to contribute!
>>> s2[2] * 2 + s2[3] + s2[-1]  # Negative indices count from the right, plus len(s), equivalent to a modulo n residue class ring
'Thank you!'
>>> s1[0] = 'o'  # str is an immutable type and cannot be modified in place; in fact, += also creates a new object
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

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
>>> s = 'OI-Wiki Thank you for reading\nWelcome to contribute!'
>>> s[:8]  # Omitting left_inclusive_index starts from the beginning
'OI-Wiki '
>>> s[8:14]  # The beauty of left-inclusive right-exclusive design: length is 14-8=6, seamlessly connecting with the previous string
'Thank you for reading'
>>> s[-4:]  # Omitting right_exclusive_index goes to the end
'to contribute!'
>>> s[8:14:2]  # Step size 2
'Thk o e'
>>> s[::-1]  # When step is -1, get the reversed string
'!etubirtnoc ot emocleW\ngnidaer rof uoy knahT ikiW-IO'
>>> s  # But the original string is unchanged
'OI-Wiki Thank you for reading\nWelcome to contribute!'

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
>>> []  # Create an empty list, note lists use square brackets
[]
>>> nums = [0, 1, 2, 3, 5, 8, 13]; nums  # Initialize a list, note the entire list can be printed directly
[0, 1, 2, 3, 5, 8, 13]
>>> nums[0] = 1; nums  # Supports index access and element modification
[1, 1, 2, 3, 5, 8, 13]
>>> nums.append(nums[-2]+nums[-1]); nums  # append() is similar to vector's push_back(), both have no return value
[1, 1, 2, 3, 5, 8, 13, 21]
>>> nums.pop()  # Pops and returns the last element, can be used as a stack; can also specify position, default is end
21
>>> nums.insert(0, 1); nums  # Similar to vector's insert(position, val)
[1, 1, 1, 2, 3, 5, 8, 13]
>>> nums.remove(1); nums  # Removes element by value (only the first occurrence), throws error if not present
[1, 1, 2, 3, 5, 8, 13]
>>> len(nums)  # Get list length, similar to vector's size(), but len() is a built-in function
7
>>> nums.reverse(); nums  # Reverse in place
[13, 8, 5, 3, 2, 1, 1]
>>> sorted(nums)  # Get a sorted list
[1, 1, 2, 3, 5, 8, 13]
>>> nums  # But the original list is not sorted
[13, 8, 5, 3, 2, 1, 1]
>>> nums.sort(); nums  # Sort in place, can specify key parameter as sorting criterion
[1, 1, 2, 3, 5, 8, 13]
>>> nums.count(1)  # Similar to std::count()
2
>>> nums.index(1)  # Returns index of first occurrence of value, throws error if not present
0
>>> nums.clear(); nums  # Similar to vector's clear()

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
>>> lst = [1, '1'] + ["2", 3.0]  # Lists can be directly added to create a new list
>>> lst  # Storing different types here is just to show it's possible, but it's not good practice
[1, '1', '2', 3.0]
>>> 3 in lst  # Practical membership test operation, strings also have this operation and support substring detection
True
>>> [1, '1'] in lst  # Only supports single member detection, won't find "subsequences"
False
>>> lst[1:3] = [2, 3]; lst  # Slice and assign, modifying the original list
[1, 2, 3, 3.0]
>>> lst[::-1]  # Get a new reversed list
[3.0, 3, 2, 1]
>>> lst *= 2; lst  # Multiplication concatenation
[1, 2, 3, 3.0, 1, 2, 3, 3.0]
>>> del lst[4:]; lst  # Could also write lst[4:] = [], del statement can be used for more than deleting sequence elements
[1, 2, 3, 3.0]

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
>>> # Create an integer array on interval [65, 70), range is also a type, can be seen as left-inclusive right-exclusive interval, third parameter is step size and can be omitted
>>> nums = list(range(65,70))  # Remember to wrap range with list()
[65, 66, 67, 68, 69]
>>> lst = [chr(x) for x in nums]  # Typical structure of list comprehension: [exp for var in iterable if cond]
>>> lst  # The above two lines can be combined into [chr(x) for x in range(65,70)]
['A', 'B', 'C', 'D', 'E']
>>> s = ''.join(lst); s # Join elements in list with empty string '' to create new string
'ABCDE'
>> list(s)  # Convert string to list of characters
['A', 'B', 'C', 'D', 'E']
>>> # If you didn't know about the s.lower() method, you might write an expression like this, which is old wine in a new bottle
>>> ''.join([chr(ord(ch) - 65 + 97) for ch in s if ch >= 'A' and ch <= 'Z'])
'abcde'

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
>>> vis = [[0] * 3] * 3  # Create a 3*3 all-zero array
>>> vis
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> vis[0][0] = 1; vis  # Why are other rows also modified?
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
>>> # First look at assignment of one-dimensional lists
>>> a1 = [0, 0, 0]; a2 = a1; a3 = a1[:]  # Lists can also be directly assigned to new variables
>>> a1[0] = 1; a1  # Modify list a1, seems normal
[1, 0, 0]
>>> a2  # Why is a2 also changed?
[1, 0, 0]
>>> a3  # a3 unchanged
[0, 0, 0]
>>> id(a1) == id(a2) and id(a1) != id(a3)  # Built-in function id() gives object's "identity value", can be analogized as address; same address means same object
True
>>> vis2 = vis[:]  # Copy the 2D list
>>> vis[0][1] = 2; vis  # vis will be modified in batch
>>> [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> vis2  # But vis2, which was copied via slicing, is also changed
>>> [[1, 2, 0], [1, 2, 0], [1, 2, 0]]
>>> id(vis) != id(vis2)  # vis and vis2 are not the same object
True
>>> # Although vis2 is not a reference to vis, the corresponding rows point to the same objects
>>> [id(vis[i]) == id(vis2[i]) for i in range(3)]
[True, True, True]
>>> # Look back at the 2D list itself
>>> [id(x) for x in vis]  # Specific numbers differ from here, but three values must be the same, indicating three identical objects
[139760373248192, 139760373248192, 139760373248192]

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
>>> vis1 = [[0] * 3 for _ in range(3)]  # It's a convention to set unused loop counter variables to underscore _
>>> # But in REPL, _ by default refers to the result of the last expression, so double underscore can also be used
>>> vis1
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> [id(x) for x in vis1]  # Specific numbers differ from here, but three values must be different, indicating three distinct objects
[139685508981248, 139685508981568, 139685508981184]
>>> vis1[0][0] = 1
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> a2[0][0] = 10  # Access and assign 2D array

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
>>> import numpy as np  # Please search for the meaning and usage of import
>>> np.empty(3) # Create empty array of capacity 3, note not initialized to 0
array([0.00000000e+000, 0.00000000e+000, 2.01191014e+180])
>>> np.zeros((3, 3)) # Create 3*3 array, initialized to 0
array([[0., 0., 0.],
       [0., 0., 0.],
       [0., 0., 0.]])
>>> a1 = np.zeros((3, 3), dtype=int) # Create 3×3 integer array
>>> a1[0][0] = 1 # Access and assign
>>> a1[0, 0] = 1 # More friendly syntax
>>> a1.shape # Shape of array
(3, 3)

>>> a1[:2, :2] # Take submatrix of first two rows and first two columns, no copy
array([[1, 0],
       [0, 0]])

>>> a1[:, [0, 2]] # Get columns 1 and 3, no copy
array([[1, 0],
       [0, 0],
       [0, 0]])
>>> np.max(a1) # Get maximum value of array
1
>>> a1.flatten() # Flatten array
array([1, 0, 0, 0, 0, 0, 0, 0, 0])

>>> np.sort(a1, axis = 1) # Sort array along row direction, return sorted result
array([[0, 0, 1],
       [0, 0, 0],
       [0, 0, 0]])
>>> a1.sort(axis = 1) # Sort array in place along row direction

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
>>> pi = 3.1415926; print('%.4f' % pi)   # Format: %[flags][width][.precision]type
3.1416
>>> '%.4f - %8f = %d' % (pi, 0.1416, 3)  # Multiple parameters on right enclosed in (), later we'll see it's actually a "tuple"
'3.1416 - 0.141600 = 3'

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,