I want to paddle, how can I let AI do the work for me and let me learn Python quickly?

AI will not eliminate programmers, but the market will eliminate programmers who cannot use AI. -- Lu Xun

What does mastering automation tools mean to programmers:

  • High-efficiency output, enhance core competitiveness (will kill you)

  • You can put more energy into paddling, drinking water and looking up at the road.

Today’s artifact is: Amazon CodeWhisperer. ---- A service that uses machine learning (ML) to help developers improve their work efficiency by generating code suggestions based on comments written by developers in natural language and code in an integrated development environment (IDE). It can help you The application provides code review, security scanning and performance optimization.

AI technology is developing at a rapid pace and is setting off a new programming paradigm change. From code generation to intelligent programming assistants, AI technology further improves development efficiency and code quality, and promotes the rapid development of software development. To help developers build applications faster and more securely, Amazon Cloud Technology launched the AI ​​programming assistant Amazon CodeWhisperer to effectively improve developer productivity.

In order to allow more developers to experience this cutting-edge intelligent programming tool, explore efficient and intelligent programming paradigms, and embrace the new changes in AI, the "Amazon CodeWhisperer Discovery Tour" event is set sail!

CodeWhisperer was trained on billions of lines of code to generate code suggestions in real time, from code snippets to full functions, based on comments and existing code. In addition to code generation, it can also be used for reference tracking and security scanning.

1. Install the plug-in

Step 1 Environment preparation

Pycharm download address (the best Python client, bar none), supports Windows, macOS, and Linux

https://www.jetbrains.com.cn/pycharm/download/?section=mac

Of course, those who are pursuing functions can choose the professional paid version. For daily use, the free community version is enough.

Step 2 Plug-in installation

Demo environment : mac * PyCharm

Tomato demonstrates PyCharm , and similar operations can be performed in IDEs such as VSCode and IntelliJ. It is also supported on mainstream operating systems such as Windows, Mac, and Linux.

Step 3 Plug-in registration

Select the lower left corner: "AWS Toolkit" > "Devoloper Tools" > "Start"

Log in as an individual user and enter your email address.

Step 4 Registration successful

After registration, you can see the effect as shown in the figure, and you can start programming.

2. AI code generation and learning

Effect 1: Write comments to automatically generate code

输入注释:
# example Python class for a simple calculator

Pop-up window has 3 states:

  • Insert Code: Insert recommended code

  • Previous : Previous recommended solution

  • Next: The next recommended solution

Just select: Enter , and the calculator methods are automatically generated, including: addition, subtraction, multiplication, and division.

# example Python class for a simple calculator
class SimpleCalculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        return a / b

Effect 2: Automatically complete code - list

A Python list is an ordered, mutable collection that can contain any type of data. It is one of the most commonly used data types in Python and can be used to store and manipulate multiple data elements.

Create a list: Use square brackets [] to create an empty list, or include some elements in square brackets to create a list with an initial value.

例如: test_list = [] 创建一个空列表
test_list = [1, 2, 3, 4, 5]
test_list.append(6)

输出:
[1, 2, 3, 4, 5, 6]

enter:test_list = [1,2

Output:test_list = [1,2,3,4,5,6,7,8,9,10]

Effect 3: Automatically complete code - for loop

Loop statements can be divided into two types: finite loop statements and infinite loop statements.

Python for loop is a loop structure used to iterate over iterable objects such as lists, tuples, strings, etc. In Python, the components of a for loop statement include the keyword for, iteration variables and iterable objects.

for i in test_list:
    if i == 5:
        print('我是five')
        break

Effect 4: Automatically complete code - conditional judgment

The conditional statement in Python is an "if statement". The difference from the writing of if statements in C language is that else if in python can be written as elif, but in C language it cannot.

The if statement is evaluated from top to bottom.

test_list = [1, 2, 3, 4, 5]
for i in test_list:
    if i == 3:
        print('我是3')
    elif i == 4:
        print('我是4')

3. Python learning based on Amazon CodeWhisperer

3.1 Variables and data types

Variables and data types: There are many data types in Python, such as integer (int), floating point number (float), string (str), list (list), tuple (tuple), dictionary (dict), etc.

Common data types in Python include:

  • Numeric types : including integer (int), floating point (float), complex (complex), etc.

  • String type : A sequence of characters enclosed in single or double quotes, such as 'hello', "world", etc.

  • List type : An ordered collection of elements enclosed in square brackets, such as [1, 2, 3], ['apple', 'banana', 'cherry'], etc.

  • Tuple type : similar to a list, but the elements of the tuple cannot be modified, such as (1, 2, 3), ('apple', 'banana', 'cherry'), etc.

  • Collection type : An unordered collection of non-repeating elements, such as {1, 2, 3}, {'apple', 'banana', 'cherry'}, etc.

  • Dictionary type : A collection of key-value pairs enclosed in curly braces, such as {'name': 'Alice', 'age': 25}, etc.

3.2 Control structure

Control structures: including conditional statements (if-elif-else), loop statements (for, while), etc.

Control structures in Python include conditional statements, loop statements, etc., which are used to control the execution flow of the program.

Conditional statements

Conditional statements are used to select different blocks of code to execute based on whether the condition is true or false. In Python, conditional statements are implemented using the if, elif, and else keywords.

语法:
Copyif condition1:
    # code block 1
elif condition2:
    # code block 2
else:
    # code block 3

Among them, condition1 and condition2 are judgment conditions. If the conditions are met, the corresponding code block will be executed.

示例:
Copyage = 18
if age < 18:
    print("未成年")
elif age >= 18 and age < 60:
    print("成年")
else:
    print("老年")
loop statement

Loop statements are used to repeatedly execute a block of code. In Python, loop statements are implemented using the for and while keywords.

语法:

for item in iterable:
    # code block

while condition:
    # code block

Among them, iterable is an iterable object, item is the element taken out during each iteration; condition is the loop condition, and when the condition is met, the code block in the loop body is executed.

示例:

# for循环
for i in range(5):
    print(i)

# while循环
count = 0
while count < 5:
    print(count)
    count += 1

3.3 Functions

Function: Use the def keyword to define functions to achieve code reuse.

A Python function is a reusable block of code that performs a specific task. Functions can receive input parameters and return results. In Python, functions are defined using the def keyword, followed by the function name and a parameter list within parentheses. The function body consists of indented blocks of code.

Here is a simple Python function example:

def greet(name):
    return "Hello, " + name + "!"
print(greet("World"))

In this example, a function named greet is defined, which accepts a parameter named name. The function returns a string containing the greeting and the name passed to the function. Tomato tests this function by calling the greet function and passing "World" as the parameter. The output should be "Hello, World!".

3.4 Classes and Objects

Classes and objects: Use the class keyword to define classes and create objects through instantiation.

Class

A class is an abstract concept used to describe a collection of objects with the same properties and methods. In Python, you can use the class keyword to define a class. For example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def say_hello(self):
        print("Hello, my name is", self.name)

In this example, we define a class named Person, which has two attributes name and age, and a method say_hello.

Object

Objects are instances of classes, that is, concrete entities. In Python, you create an object by calling a class. For example:

p = Person("Tom", 20)

In this example, we create a Person object named p and pass it two parameters "Tom" and 20.

Objects can access the properties and methods defined in the class. For example:

Copyp.name = "Jerry"
p.age = 25
p.say_hello()

In this example, we set the name and age attributes respectively for the p object, and called the say_hello method. The output is: "Hello, my name is Jerry".

3.5 File operations

File operations: Use the open() function to open the file, and read(), write() and other methods to perform file reading and writing operations.

Python provides many built-in functions and modules to handle file operations. The following are some commonly used file operation functions and modules:

Open a file : Use the open() function to open a file and return a file object. For example:

file = open("example.txt", "r")

In this example, we opened a file called example.txt and opened it in read-only mode ("r").

Read the file : Use the read() method to read all the contents of the file. For example:

content = file.read()
print(content)

In this example, we read the entire contents of the file and print it out.

Writing to a file : Use the write() method to write text to a file. For example:

Copyfile = open("example.txt", "w")
file.write("Hello, world!")
file.close()

In this example, we opened a file named example.txt in write mode ("w") and wrote the string "Hello, world!" into it.

Close the file : Use the close() method to close the open file. For example:

Copyfile.close()

3.6 Exception handling

Exception handling: Use try-except statements to catch and handle exceptions.

In Python, exception handling is a mechanism for handling errors or unusual situations that may occur while a program is running. When an error is encountered during program execution, the Python interpreter will raise an exception. If there is no appropriate handling mechanism, the program will terminate and display an error message. To avoid this from happening, we can use exception handling to catch and handle these exceptions.

Exception handling in Python is usually implemented using try-except statements. The try block contains code that may throw an exception, while the except block contains code that handles exceptions. If the code in the try block raises an exception, the code following the try block will be skipped, and the Python interpreter will look for an except block that matches the exception and execute the code in it.

Here is a simple Python exception handling example:

x = 1 / 0
except ZeroDivisionError:
    print("除数不能为零")

In this example, we try to perform a divide-by-zero operation, which raises a ZeroDivisionError exception. Since we use an except block after the try block to catch this exception, when the exception occurs, the program does not terminate, but executes the code in the except block and prints out "The divisor cannot be zero".

In addition to using specific exception types to catch exceptions, we can also use a generic except block to catch all types of exceptions. For example:

# some code that may raise an exception
except Exception as e:
    print("发生了一个错误:", e)

In this example, we have used a generic except block to catch all types of exceptions and store the exception object in the variable e. Then, we can print out the exception information.

3.7 List comprehension

Python list comprehensions are a quick way to create lists, using a concise syntax structure to generate a new list. A list comprehension usually consists of an iterable object (such as a list, tuple, set, etc.) and an expression that is used to evaluate each element in the new list.

The syntax of list comprehension is as follows:

[expression for item in iterable if condition]

in:

  • expression: The expression used to evaluate each element in the new list.

  • item: Each element obtained from the iterable object.

  • iterable: an iterable object, such as a list, tuple, set, etc.

  • condition: Optional conditional expression, used to filter elements that meet the condition.

For example, we can use list comprehensions to create a list containing all even numbers between 1 and 10:

even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)  # 输出:[2, 4, 6, 8, 10]

In this example, I used range(1, 11) as the iterable object, x represents each element obtained from the iterable object, and x % 2 == 0 as the conditional expression to filter out even numbers.

4. AI citation tracking

Code reference tracing is a debugging technique that helps developers determine the reference relationships of variables and functions in a program. While the program is running, every variable and function may be referenced or called by other code.

Through code reference tracking, developers can view these reference relationships to better understand the execution process and logic of the program.

Code reference tracing is often used to debug complex programs, especially when processing large amounts of data or executing complex algorithms. It helps us find bugs and bottlenecks in our programs and provides suggestions on how to optimize the code. In addition, code reference tracking can also help us better understand the execution time and memory usage of the code, so as to better optimize the performance of the program.

5. AI security scanning

Code security scanning is a method of checking for security vulnerabilities in your code. It helps enterprises ensure that the code in their code base does not contain potential security vulnerabilities, thereby protecting the enterprise's data and assets.

Code security scanning can be done through the Amazon CodeWhisperer automated tool, which can check for common vulnerabilities in the code, such as SQL injection, cross-site scripting (XSS), and cross-site request forgery (CSRF). In addition, code security scanning can help developers identify and fix errors and irregularities in their code.

6. Use experience

After initial use, I already couldn’t put it down, mainly reflected in the following points:

  • Smooth to use : Amazon CodeWhisperer has a smooth user experience. It can generate code through comments, or use AI technology to recommend the code I am about to write. This is very friendly to beginners and can quickly learn common interface calling methods and syntax. It is simply an artifact for quickly learning Python.

  • Rich documentation and learning resources : Amazon CodeWhisperer provides detailed and rich documentation and learning resources, even including videos, which is developer-friendly and provides tutorials for advanced operations, such as automated code testing, etc.

  • Multi-language and platform support : In addition to Tomato's demo environment: mac_pycharm_Python. CodeWhisperer supports up to 15 development languages ​​and can also automatically generate code and more.

  • Syntax error detection : CodeWhisperer can detect potential syntax errors in your code and give corresponding tips and repair suggestions.

  • Real-time code suggestions : CodeWhisperer can provide real-time code suggestions and auto-complete functions based on the code snippets you enter, allowing you to write code faster.

In short, CodeWhisperer is a very practical code editor plug-in that can help me improve programming efficiency and code quality. If you are also a developer, you may consider using CodeWhisperer to do something.

Guess you like

Origin blog.csdn.net/weixin_39032019/article/details/133385867