❥ ❥ the most complete python operation list in the whole network is coming ❥ ❥ (recommended Collection) (^ -)

Keywords: Python Pycharm list pygame

Chapter 4 operation list

4.1 traversing the entire list
You often need to traverse all the elements of the list and perform the same operation on each element. For example, in a game, you may need to translate each interface element the same distance; For a list containing numbers, you may need to perform the same statistical operation on each element; In a web site, you may want to display each title in the article list. When you need to perform the same operation on each element in the list, you can use the for loop in Python.

Suppose we have a list of magicians, and we need to print out the names of each magician. To do this, you can get each name in the list separately, but this can lead to multiple problems. For example, if the list is long, it will contain a lot of duplicate code. In addition, the code must be modified whenever the length of the list changes. By using the for loop, Python can handle these problems.

Next, use the for loop to print all the names in the magician list:

magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(magician)
cats = ['alice', 'bob', 'carolina']
for cat in cats:
    pass
    result: IndentationError: expected an indented block (3265874414.py, line 5)
  File "/var/folders/61/c7zbwys51jx0f5_c9hl6jcfm0000gp/T/ipykernel_44725/3265874414.py", line 5
    for cat in cats:
                    ^
IndentationError: expected an indented block

4.1.1 in depth study cycle

The concept of loop is important because it is one of the common ways for computers to automate repetitive work. For example, in the simple loop used in magicians.py earlier, Python will first read the first line of code:

for magician in magicians:

This line of code lets Python get the first value 'alice' in the list magicians and associate it with the variable magician. Next, python reads the next line of code:

print(magician)

In addition, when writing a for loop, you can assign any name to the temporary variable associated with each value in the list in turn. However, it is helpful to choose meaningful names that describe individual list elements. For example, for kitten list, dog list and general list, it is a good choice to write the first line of the for loop as follows:

for cat in cats:
    pass
for dog in dogs:
    pass
for item in list_of_items:
    pass

These naming conventions help you understand what will happen to each element in the for loop. Using singular and plural names can help you determine whether the code snippet is dealing with a single list element or an entire list.
4.1.2 do more in the for loop

In a for loop, you can do anything on each element. Let's extend the previous example. For each magician, print a message indicating that his performance is wonderful.

magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was as greet trick!")``
    result:
Alice, that was as greet trick!
Bob, that was as greet trick!
Carolina, that was as greet trick!

In the for loop, you can include as many lines of code as you want. After the code line for magician in magicians, each indented code line is part of a loop and will be executed once for each value in the list. Therefore, you can perform any number of operations on each value in the list.
Now add another line of code to tell each magician that we look forward to his next performance:

magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was as greet trick!")
    print(f"I can't wait to see yr next trick, {magician.title()}")
    result: Alice, that was as greet trick!
I can't wait to see yr next trick, Alice
Bob, that was as greet trick!
I can't wait to see yr next trick, Bob
Carolina, that was as greet trick!
I can't wait to see yr next trick, Carolina

4.1.3 perform some operations after the for loop ends
What happens after the for loop ends? Usually, you need to provide summary output or then perform other tasks that the program must complete.

After the for loop, the code without indentation is executed only once and will not be repeated. Let's print a message of thanks to all Magicians for their wonderful performance. If you want to print a thank you message to all magicians after the message printed to all magicians, you need to put the corresponding code after the for loop without indentation:

agicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was as greet trick!")
    print(f"I can't wait to see yr next trick, {magician.title()}")
print("No indent")
result: Alice, that was as greet trick!
I can't wait to see yr next trick, Alice
Bob, that was as greet trick!
I can't wait to see yr next trick, Bob
Carolina, that was as greet trick!
I can't wait to see yr next trick, Carolina
 No indent
magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was as greet trick!")
    print(f"I can't wait to see yr next trick, {magician.title()}")
print("No indent")
print(magician)
del magician
print(magician)
result: Alice, that was as greet trick!
I can't wait to see yr next trick, Alice
Bob, that was as greet trick!
I can't wait to see yr next trick, Bob
Carolina, that was as greet trick!
I can't wait to see yr next trick, Carolina
 No indent
carolina
NameError: name 'magician' is not defined
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/var/folders/61/c7zbwys51jx0f5_c9hl6jcfm0000gp/T/ipykernel_44725/1810894605.py in <module>
      6 print(magician)
      7 del magician
----> 8 print(magician)

NameError: name 'magician' is not defined

Variables in Python do not need to be declared, so we are confused about its life cycle. For example, k of the for loop in C language will disappear outside the for loop, but magician still exists outside the loop in Python**

In fact, variables in Python are automatically recycled by the compiler (of course, you can also use del to force recycling)
4.2 avoiding indentation errors
Python uses indentation to determine the relationship between a line of code and the previous line of code. In the previous example, the lines of code that display messages to magicians are part of the for loop because they are indented. Python makes code easier to read by using indentation. Simply put, it requires you to use indentation to keep your code clean and structured. In a longer Python program, you will see code blocks with different indentations, so you can have a general understanding of the organizational structure of the program.

When you start writing code that must be indented correctly, you need to pay attention to some common indentation errors. For example, programmers sometimes indent code blocks that do not need to be indented, but forget to indent code blocks that must be indented. Viewing examples of such errors can help you avoid them later and fix them when they appear in the program.
Let's look at some common indentation errors.
4.2.1 forget to indent
Be sure to indent lines of code that are part of a loop after a for statement. If you forget to indent, Python will remind you:

magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was as greet trick!")
result: IndentationError: expected an indented block (77887116.py, line 3)
  File "/var/folders/61/c7zbwys51jx0f5_c9hl6jcfm0000gp/T/ipykernel_44725/77887116.py", line 3
    print(f"{magician.title()}, that was as greet trick!")
    ^
IndentationError: expected an indented block

4.2.2 forget to indent additional lines of code

Sometimes loops can run without reporting errors, but the results can be unexpected. This happens when you try to perform multiple tasks in a loop and forget to indent some of the lines of code.

For example, this happens if you forget to indent the second line of code in the loop (it tells each magician that we expect him to perform next time)

magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was as greet trick!")
print(f"I can't wait to see yr next trick, {magician.title()}")
result: Alice, that was as greet trick!
Bob, that was as greet trick!
Carolina, that was as greet trick!
I can't wait to see yr next trick, Carolina

This is a logical error. Syntactically, these Python codes are legal, but due to logical errors, the results do not meet expectations. If you expect an operation to be performed once for each list element, but it is only performed once in total, determine whether you need to indent one or more lines of code.
4.2.3 unnecessary indentation

If you accidentally indent a line of code that does not need to be indented, Python will point out this

message = "Hello Python world!"
    print(message)
    result: IndentationError: unexpected indent (2495908521.py, line 2)
  File "/var/folders/61/c7zbwys51jx0f5_c9hl6jcfm0000gp/T/ipykernel_44725/2495908521.py", line 2
    print(message)
    ^
IndentationError: unexpected indent

To avoid unexpected indentation errors, indent only the code that needs to be indented. In the previously written program, only the code to be executed on each element in the for loop needs to be indented.
4.2.4 unnecessary indentation after cycle

If you accidentally indent the code that should be executed at the end of the loop, the code will be repeated for each list element. In some cases, this may cause Python to report syntax errors, but in most cases, it will only cause logical errors.

For example, what happens if you accidentally indent a line of code that thanks all the magicians for their wonderful performance?

magicians = ['alice', 'bob', 'carolina']
for magician in magicians:
    print(f"{magician.title()}, that was as greet trick!")
    print(f"I can't wait to see yr next trick, {magician.title()}")
    print()
    print("Thank you everyone, that was a great magic show!")
    result: Alice, that was as greet trick!
I can't wait to see yr next trick, Alice

Thank you everyone, that was a great magic show!
Bob, that was as greet trick!
I can't wait to see yr next trick, Bob

Thank you everyone, that was a great magic show!
Carolina, that was as greet trick!
I can't wait to see yr next trick, Carolina

Thank you everyone, that was a great magic show!

4.2.5 colon missing

The colon at the end of the for statement tells Python that the next line is the first line of the loop.

magicians = ['alice', 'bob', 'carolina']
for magician in magicians
    print(f"{magician.title()}, that was as greet trick!")
    result: SyntaxError: invalid syntax (3390044093.py, line 2)
  File "/var/folders/61/c7zbwys51jx0f5_c9hl6jcfm0000gp/T/ipykernel_44725/3390044093.py", line 2
    for magician in magicians
                             ^
SyntaxError: invalid syntax

Practice it

Contact 4.1 pizza

Think of at least three pizzas you like, store their names in a list, and then use the for loop to print out the name of each pizza.

  • Modify the for loop so that it prints a sentence containing the name of the pizza, not just the name of the pizza. For each pizza, one line of output is displayed. Here is an example.
`I like pepperoni pizza.`
  • Add a line of code at the end of the program that is not in the for loop to indicate how much you like pizza. The output should include a message for each pizza and a concluding sentence. Here is an example.
`I really love pizza!`
noodles = ['Beef noodles', 'Facial patch', 'Minced pork noodles']
for noodle in noodles:
    print(f"I love eating{noodle}!")
print("I like all pasta!")
I like beef noodles!
I like noodles!
I like saozi noodles!
I like all pasta!

Exercise 4-2: Animals

Think of at least three animals with common characteristics, store their names in a list, and then use the for loop to print out the names of each animal.

  • Modify this program to print a sentence for each animal. Here is an example.
`A dog would make a great pet.`
  • Add a line of code at the end of the program to point out what these animals have in common, such as printing the following sentence.
`Any of these animals would make a great pet!`

4.3 creating a list of values

There are many reasons why you need to store a set of numbers. For example, in a game, you need to track the position of each character, and you may also need to track several of the player's highest scores; In data visualization, almost all data is a collection of numbers (such as temperature, distance, population, longitude and latitude).

Lists are ideal for storing collections of numbers, and Python provides many tools to help you deal with lists of numbers efficiently. Knowing how to use these tools effectively, your code will work well even if the list contains millions of elements.

4.3.1 using the function range()

The Python function range () allows you to easily generate a series of numbers. For example, you can print a series of numbers using the function range() as follows:

# Left closed right open
for k in range(1, 5):
    print(k)
    Results: 1
2
3
4
``

```python
 Left default is 0
for k in range(5):
    print(k)
    Result: 0
1
2
3
4

4.3.2 creating a list of numbers using range()

To create a list of numbers, use the function list() to convert the result of range() directly into a list. If you take range () as an argument to list (), the output will be a list of numbers.

In the example in the previous section, you just print out a series of numbers. To convert this set of numbers to a list, use list():

numbers = list(range(1, 6))
print(numbers)
numbers = list(range(6))
print(numbers)
result:[1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5]

Including step size

`range(left, right, step)`
even_numbers = list(range(2, 11, 2))
odd_numbers = list(range(1, 11, 2))
print(even_numbers)
print(odd_numbers)
result:[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Negative numbers are also OK

print(list(range(-10, 6, 3)))
print(list(range(10, -6, -3)))
print(list(range(-10, 6, -3)))#
print(list(range(10, -6, 3)))#
result:[-10, -7, -4, -1, 2, 5]
[10, 7, 4, 1, -2, -5]
[]
[]

You can create almost any set of numbers you need using the function range(). For example, how to create a list that contains the squares of the first 10 integers (1 to 10)? In Python, the power operation is represented by two asterisks (* *). The following code demonstrates how to add the squares of the first 10 integers to a list:

squares = [] 
for value in range(1, 11): 
    square = value ** 2
    squares.append(square)
print(squares)
result:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

4.3.3 perform simple statistical calculations on the list of numbers

There are several Python functions dedicated to dealing with numeric lists. For example, you can easily find the maximum, minimum, and sum of a list of numbers:

digits = list(range(1, 12))
print(f"min = {min(digits)}")
print(f"max = {max(digits)}")
print(f"sum = {sum(digits)}")
result: min = 1
max = 11
sum = 66

4.3.4 list analysis

The way to generate the list squares described above includes three or four lines of code, and list parsing allows you to generate such a list by writing only one line of code. List parsing combines the for loop and the code that creates the new element into one line, and automatically attaches the new element. Not all books for beginners will introduce list parsing. The reason why list parsing is introduced here is that you are likely to encounter it when you start reading the code written by others.

The following example uses list parsing to create a list of squares you saw earlier:

squares = [f"{k}^2={k**2}" for k in range(1, 11)]
print(squares)
result:['1^2=1', '2^2=4', '3^2=9', '4^2=16', '5^2=25', '6^2=36', '7^2=49', '8^2=64', '9^2=81', '10^2=100']

Try it yourself

Exercise 4-3: count to 20

One for cycle is used to print 1 ~ 20 (including).

for k in range(20):
    print(k+1)
    Results: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Exercise 4-4: one million

Create a list containing numbers from 1 to 1 000 000, and then print them out using a for loop. (if the output time is too long, press Ctrl + C to stop the output or close the output window.)

Exercise 4-5: sum a million

Create a list of 1 ~ 1 000 000, and then use min() and max() to verify that the list really starts from 1 and ends at 1 000 000. In addition, call the function sum() on this list to see how long it takes Python to add a million numbers.

numbers = list(range(1, 1_000_000+1))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
Results: 1
1000000
500000500000

Exercise 4-6: odd numbers

Create a list of odd numbers from 1 to 20 by specifying the third parameter to the function range(), and then print them out using a for loop.

odd_numbers = list(range(1, 20, 2))
print(odd_numbers)
result:[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

Exercise 4-7:3 multiples

Create a list containing 3 ~ 30 numbers that can be divided by 3, and then use a for loop to print out the numbers in the list.
Exercise 4-8: cube

Multiplying the same number three times is called cubic. For example, in Python, the cube of 2 is represented by 2 * * 3. Please create a list containing the cubes of the first 10 integers (1 ~ 10), and then use a for loop to print these cubes.

t = [k**3 for k in range(1, 11)]
print(t)
result:[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

Exercise 4-9: cube analysis

Use list parsing to generate a list containing the cubes of the first 10 integers.
99 multiplication table

for k in range(1, 10):
    for m in range(1, k+1):
        print(f'{k}x{m}={k*m:2d}', end='\t')
    print()
    result:
1x1= 1	
2x1= 2	2x2= 4	
3x1= 3	3x2= 6	3x3= 9	
4x1= 4	4x2= 8	4x3=12	4x4=16	
5x1= 5	5x2=10	5x3=15	5x4=20	5x5=25	
6x1= 6	6x2=12	6x3=18	6x4=24	6x5=30	6x6=36	
7x1= 7	7x2=14	7x3=21	7x4=28	7x5=35	7x6=42	7x7=49	
8x1= 8	8x2=16	8x3=24	8x4=32	8x5=40	8x6=48	8x7=56	8x8=64	
9x1= 9	9x2=18	9x3=27	9x4=36	9x5=45	9x6=54	9x7=63	9x8=72	9x9=81

4.4 use part of the list

In Chapter 3, you learned how to access a single list element. In this chapter, you have been learning how to deal with all the elements of the list. You can also work with some elements of the list, which Python calls slicing.

`4.4.1 slicing

To create a slice, specify the index of the first and last element to use. Like the function range(), Python stops after reaching the element before the second index. To output the first three elements in the list, you need to specify indexes 0 and 3, which returns elements with indexes 0, 1, and 2.

The following example deals with a sports team member list:

players = ['All red Zen', 'Xie Sichang', 'Zong Yuan Wang', 'Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']
print(players[0:3])
print(players[:3])
result:['All red Zen', 'Xie Sichang', 'Zong Yuan Wang']
['All red Zen', 'Xie Sichang', 'Zong Yuan Wang']

Left closed right open

players = ['All red Zen', 'Xie Sichang', 'Zong Yuan Wang', 'Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']
print(players[1:4])
result: players = ['All red Zen', 'Xie Sichang', 'Zong Yuan Wang', 'Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']
print(players[1:4])
['Xie Sichang', 'Zong Yuan Wang', 'Wang Han']
players = ['All red Zen', 'Xie Sichang', 'Zong Yuan Wang', 'Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']
print(players[3:])
['Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']

Negative index

print(players[-3:])
['Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']

Including step size

players = ['All red Zen', 'Xie Sichang', 'Zong Yuan Wang', 'Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']
print(players[1:5:2])
print(players[5:1:-3])
print(players[::-1])
['Xie Sichang', 'Wang Han']
['Zhangjiaqi', 'Zong Yuan Wang']
['Yang Jian', 'Zhangjiaqi', 'Chen Yuxi', 'Wang Han', 'Zong Yuan Wang', 'Xie Sichang', 'All red Zen']

4.4.2 traversal slice

If you want to traverse some elements of the list, you can use slicing in the for loop. The following example traverses the first three team members and prints their names:

players = ['All red Zen', 'Xie Sichang', 'Zong Yuan Wang', 'Wang Han', 'Chen Yuxi', 'Zhangjiaqi', 'Yang Jian']
for player in players:
    print(player)
print('-' * 80)
for player in players[-3:]:
    print(player)
    All red Zen
 Xie Sichang
 Zong Yuan Wang
 Wang Han
 Chen Yuxi
 Zhangjiaqi
 Yang Jian
--------------------------------------------------------------------------------
Chen Yuxi
 Zhangjiaqi
 Yang Jian

4.4.3 copy list

We often need to create new lists based on existing lists. Here's how a copy list works and a situation where a copy list can be of great help. To copy a list, create a slice that contains the entire list by omitting both the start index and the end index ([:]). This allows Python to create a slice that starts with the first element and ends with the last element, a copy of the entire list.

For example, suppose you have a list of your four favorite foods, and you want to create another list that includes all the foods a friend likes. However, this friend also likes the food you like, so you can create this list by copying:

my_foods = ['McDonald's', 'Kentucky Fried Chicken', 'Subway']
friend_foods = my_foods
friend_foods[0] = 'Country chicken'
print(my_foods[0])

Country chicken

reason: list Assignment between does not create a new list, Equivalent to a nickname of the original list**

If you want to put one list Assign to a new list, need`new_list = old_list[:]`or`new_list = old_list.copy()`
my_foods = ['McDonald's', 'Kentucky Fried Chicken', 'Subway']
friend_foods = my_foods[:]#.copy()
friend_foods[0] = 'Country chicken'
print(my_foods)
result:['McDonald's', 'Kentucky Fried Chicken', 'Subway']

4.5 tuple

Lists are ideal for storing data sets that may change during program execution. The list can be modified, which is very important to deal with the list of users on the website or the list of characters in the game. However, sometimes you need to create a series of immutable elements, and tuples can meet this requirement. Python calls immutable values and immutable lists tuples.

4.5.1 defining tuples

Tuples look like lists, but are identified by parentheses rather than square brackets. Once a tuple is defined, its elements can be accessed using an index, just like a list element.

For example, if you have a rectangle whose size should not change, you can store its length and width in a tuple to ensure that they cannot be modified:

shape = (400, 300)
print(f'The rectangular shape is:{shape[0]}x{shape[1]}')
The rectangular shape is:400x300

Let's try to modify an element of tuple shape to see the result:

shape[0] = 800
TypeError: 'tuple' object does not support item assignment
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/61/c7zbwys51jx0f5_c9hl6jcfm0000gp/T/ipykernel_44725/3748989597.py in <module>
----> 1 shape[0] = 800

TypeError: 'tuple' object does not support item assignment

Note: only one element tuple, comma is required

my_t = (3)
print(type(my_t))
my_t = (3,)
print(type(my_t))
result:<class 'int'>
<class 'tuple'>

4.5.2 traversing all values in tuples

Like a list, you can also use the for loop to traverse all values in a tuple:

shape = (400, 300)
for each in shape:
    print(each)
    Result: 400
300

4.5.3 modifying tuple variables

Although the element of the tuple cannot be modified, the variable storing the tuple can be assigned a value. Therefore, if you want to modify the size of the above rectangle, you can redefine the whole tuple:

shape = (400, 300)
for each in shape:
    print(each)
shape = (800, 600)
print('-' * 80)
for each in shape:
    print(each)
    Result: 400
300
--------------------------------------------------------------------------------
800
600

4.6 setting code format

As you write longer and longer programs, it is necessary to understand some code formatting conventions. Please take the time to make your code as easy to read as possible. This will help you master what the program does and help others understand the code you write.

To ensure that everyone writes code with roughly the same structure, python programmers follow some formatting conventions. After learning to write neat python, you can understand the overall structure of Python code written by others - as long as they follow the same guidelines as you. To become a professional programmer, follow these guidelines from now on to form good habits.

4.6.1 format setting guide

To propose Python language modification suggestions, you need to write Python Enhancement Proposal (PEP). PEP 8 is one of the oldest peps and provides Python programmers with code formatting guidelines. PEP 8 is very long, but it is basically related to the complex coding structure.

The authors of the Python formatting guide know that code is read more than written. When the code is written, we need to read it when debugging. When adding new functions to the program, it takes a long time to read; When sharing code with other programmers, they will also read it.

If you have to choose between making your code easy to write and easy to read, Python programmers almost always choose the latter. The following guidelines can help you write clear code from the beginning.

4.6.2 indent

PEP 8 recommends four spaces for each level of indentation. This not only improves readability, but also leaves enough multi-level indentation space.

In word processing documents, people often use tabs instead of spaces to indent. This works well for word processing documents, but mixing tabs and spaces can confuse the Python interpreter. Each text editor provides a setting that converts the tabs you enter into a specified number of spaces. You should definitely use tab keys when writing code, but be sure to set the editor to insert spaces instead of tabs in the document.

Mixing tabs and spaces in a program can lead to problems that are extremely difficult to troubleshoot. If you mix tabs and spaces, you can convert all tabs in the file to spaces, which is provided by most editors.

4.6.3 president

Many Python programmers recommend no more than 80 characters per line. When such guidelines were first developed, in most computers, the terminal window could only hold 79 characters per line. At present, the number of characters per line of computer screen is much more. Why use the standard length of 79 characters? There are other reasons. Professional programmers usually open multiple files on the same screen. Using the standard manager allows them to see the complete lines of each file when they open two or three files side by side on the screen. PEP 8 also recommends that the length of comments should not exceed 72 characters, because some tools automatically generate documents for large projects and add formatting characters at the beginning of each line of comments.

The guideline on President in PEP 8 is not an insurmountable red line. Some groups set the maximum president to 99 characters. During your study, you don't have to think too much about the president of the code, but don't forget that almost everyone follows the PEP 8 guide when writing programs cooperatively. In most editors, you can set a visual sign (usually a vertical line) to let you know where the line you can't cross is.

Note that Appendix B describes how to configure the text editor to insert four spaces when you press the tab key and display a vertical reference line to help you comply with the Convention of 79 characters or less.

4.6.4 blank lines

To separate different parts of the program, use blank lines. You should use blank lines to organize program files, but you can't abuse them. As long as you do as the examples in this book show, you can grasp the balance. For example, if you have five lines of code to create a list and three lines of code to process the list, it is appropriate to separate the two parts with a blank line. However, you should not separate them with three or four blank lines.

Blank lines will not affect the operation of the code, but will affect the readability of the code. The Python interpreter interprets the code according to the horizontal indentation, but does not care about the vertical spacing.

4.6.5 other format setting guidelines

PEP 8 has many other formatting suggestions, but most of the procedures for these compass pairs are more complex than those mentioned in this book so far. When we introduce the more complex Python structure, let's share the related PEP 8 guide.
Give it a try**

Exercise 4-14: PEP 8

Please visit the python website and search "pep 8 - Style Guide for Python Code" to read the PEP 8 formatting guide. At present, these guidelines are not applicable, but you can browse them roughly.

Exercise 4-15: Code Review

Select three from the procedures written in this chapter and modify them according to PEP 8 guidelines.

  • Four spaces are used for each level of indentation. Set the text editor you use to insert four spaces when you press Tab. If you haven't already done so, do it now (see Appendix B for how to set it up).
  • Do not exceed 80 characters per line. Set the editor you use to display a vertical reference line at the 80th character.
  • Do not use too many blank lines in program files.

Posted by Rocu on Wed, 13 Oct 2021 08:58:11 -0700