What software to use to write code in python, steps to write code in python

Hello everyone, let me share with you what software is used to write python code. Many people still don’t know this. Let’s explain it in detail below. Now let’s take a look!

Hello everyone, let me share with you how to write code in Python and jump to the next line in the editor. Many people still don’t know this. PHP vs. PYTHON: a detailed comparison based on syntax, functions, applications, etc. Let’s explain it in detail below ```*`` Now let’s take a look!

It’s so easy to write Python code yourself using Python code

As a powerful and flexible programming language, Python can be used in various fields and has the characteristic of being "omnipotent". Synonyms : python for statement usage .

Python can even replace people and write Python code by yourself ```*`` and it is very simple. You only need to learn the basic knowledge of Python chatgpt writing ideas .

This article introduces how to generate Python code yourself using Python code, please read below.

required knowledge

1. File writing operation

In Python, you can use the built-in function open() to open an existing file or create a new file. open(file name, access mode)

Access mode:

  • r: Open the file in read-only mode, and the file pointer will be placed at the beginning of the file. After opening the file, read the contents starting from the beginning of the file.
  • w: Open a file for writing from the beginning. The file pointer is also placed at the beginning of the file. If the file already exists, it will be overwritten. Create a new file if the file does not exist.
  • a: Open a file for append writing. If the file already exists, the file pointer will be placed at the end of the file. In other words, new content will be written after existing content. If the file does not exist, a new file is created and written from scratch.

In addition, there are many other modes: rb, wb, ab, r+, w+, a+, rb+, wb+, ab+, which will not be introduced one by one.

This article uses w mode and a mode. The open() function is usually used in conjunction with the context management keyword with.

For example:

with open("test.txt", "w") as f:
    f.write('写入的内容')

Created test.txt file:
Insert image description here
2.Python code file extension

Python code is a text file with a .py extension (file extension), which can be run wherever a Python interpreter is installed. If you use Python to generate a file with a .py suffix, the generated file can be recognized by the Python interpreter.

Therefore, the way to automatically write Python code with Python is to create a .py file and write the code to be generated in the file.

Content is written using strings, and the written content needs to meet Python's encoding specifications.

Write a Hello World program

After introducing the method, first write a Hello World program to facilitate understanding.

python_file = "hello_world.py"
with open(python_file, "w") as f:
    f.write("# coding=utf-8\n")
    f.write("print('Hello World!')\n")

Generated hello_world.py code:

# coding=utf-8
print('Hello World!')

The generated code file hello_world.py can be run directly, which shows that the Python interpreter treats automatically generated .py files and manually written .py files equally, and both can run normally.

Based on the above content, the path to automatically writing Python code with Python has been completed.

Let's continue to analyze how to meet various coding standards of Python (handling the details of coding standards), and think about which scenarios can use Python to automatically write code.

Some details introduction and analysis

python_file = "auto_gen_print.py"
with open(python_file, "w") as f:
    f.write("# coding=utf-8\n\n")
    f.write("for i in range(10):\n")
    f.write("    print(i)\n")

Generated auto_gen_print.py code:

# coding=utf-8

for i in range(10):
    print(i)

After the generated code is run, the 10 numbers 0-9 will be printed in a loop on the console.

Code wrapping and indentation processing:

  • Line break: To break lines in the generated code, add a line break character \n after each line of code when writing content. One \n represents a newline, and the corresponding number of newline characters must be added where a blank line is required.
  • Indentation: When writing code in an IDE (such as PyCharm), the Tab key is often used to control the indentation of the code. The corresponding character is \t. When automatically generating code, \t can be used to indicate indentation.

However, after opening the generated code in PyCharm, I found that the generated indentation did not meet the PEP coding specifications. Four spaces must be used to represent the indentation to meet the PEP coding specifications. However, the indentation generated by \t does not affect code execution and code readability, and can be used with confidence.

python_file = "auto_gen_print.py"
with open(python_file, "a") as f:
    f.write("\n")
    f.write("print('-' * 20)\n")
    for i in range(10):
        f.write("print({})\n".format(i))

Add additional code in auto_gen_print.py:

print('-' * 20)
print(0)
print(1)
print(2)
print(3)
print(4)
print(5)
print(6)
print(7)
print(8)
print(9)

The above auto_gen_print.py uses w mode when writing for the first time, and a mode when writing for the second time.

For the code that is called repeatedly, the above auto_gen_print.py generates a for loop for the first time, and directly writes N lines of function code for the second time.

Processing of repeated logic:

  • Generate loops: The way to handle repetitive logic in Python is generally to use loops, so you can generate loops in the code and use loops to execute repeated code.
  • Repeated calls: When automatically generating code, advance the loop to the script used to generate the code. After executing the script, repeated code is generated, replacing handwriting and copy-pasting.

For repeated business logic, there is no difference in the running results of the two generation methods.

Thinking from the perspective of automatically generating code, the first method generates a loop code. The second method is to repeatedly generate a line (or multiple lines) of code, using automatic generation to avoid repeated code writing and repeated copying and pasting.

The second way to repeatedly generate code is more likely to be where automatic code generation comes in. Think about it, if you encounter a scenario where business logic is repeated and it is not suitable to use loops or function or class encapsulation, you might as well try to automatically generate code.

Another core function of automatically generating code is that it can be repeatedly generated.

It is not difficult to find that the code used to generate the loop previously has 5 lines, but the loop code only has two lines. Using the automatic generation method, the code is even more. However, the point is that these 5 lines of code can be executed N times. As long as a few parameters are adjusted, a new Python code file can be generated every time it is re-executed.

In practical applications, taking into account repeated use, the method of automatically generating code can definitely "do a lot".

Case presentation

The following case demonstrates using code to generate a piece of code for drawing a square.

python_file = "auto_gen_square.py"
with open(python_file, "w", encoding='utf-8') as f:
    f.write("# coding=utf-8\n")
    f.write("import turtle as t\n\n")
    point = [(-50, 50), (50, 50), (50, -50), (-50, -50)]
    f.write("t.title('DrawSquare(公众号:小斌哥ge)')\n")
    f.write("t.setup(400, 300, 100, 200)\n")
    f.write("t.speed(5)\n")
    f.write("t.penup()\n")
    f.write("t.goto({})\n".format(point[0]))
    f.write("t.pendown()\n")
    for p in point[1:]:
        f.write("t.goto({})\n".format(p))
    f.write("t.goto({})\n".format(point[0]))
    f.write("t.penup()\n")
    f.write("t.goto(100, 0)\n")
    f.write("t.done()\n")

Generated auto_gen_square.py code:

# coding=utf-8
import turtle as t

t.title('DrawSquare(公众号:小斌哥ge)')
t.setup(400, 300, 100, 200)
t.speed(5)
t.penup()
t.goto((-50, 50))
t.pendown()
t.goto((50, 50))
t.goto((50, -50))
t.goto((-50, -50))
t.goto((-50, 50))
t.penup()
t.goto(100, 0)
t.done()

Results of running auto_gen_square.py:
Insert image description here

Run the automatically generated code and draw a square using the turtle library.

Summarize

  1. This article introduces the method of automatically generating code using Python and explains the basic implementation principles and knowledge.

  2. This article analyzes some detailed processing methods when automatically generating code. More specific situations can be supplemented according to your application scenarios.

  3. This article shares a practical case. You can give full play to your ingenuity and apply the method of automatically generating code to more scenarios for your own use.

If this article is helpful to you or can give you some inspiration, you are welcome to like, collect, comment, and follow.

Related reading
Python file reading and writing operations

Guess you like

Origin blog.csdn.net/mynote/article/details/133531916