ChatGPT入门基础课05——如何用AI来写代码

ChatGPT入门基础课05——如何用AI来写代码

编码文章call10242025-02-14 22:21:3029A+A-

ChatGPT可以用来进行代码生成、代码调试、代码优化、格式化处理等,从而实现代码由无到有,由有到优的转变,你甚至可以用类似文章提纲的方式,直接实现一个简单项目的从零到1,它可以处理40多种编程语言,涉及c、c++、java、js、html、python、sql等主流编程语言,甚至是小众的如金融类软件通达信的回测语言都有令人惊喜的表现。

Very Old

Old

Recent

Bleeding Edge

BASIC

Perl

Swift

Kotlin

Assembly

Pascal

TypeScript

Julia

Fortran

PHP

Rust

Crystal

Lisp

Prolog

Kotlin/Native

Racket

COBOL

C

Julia (GPU)

Lua

Algol

PL/I

Go

Zig

SNOBOL

C++

Dart

Nim

RPG

Smalltalk

Elixir

Crystal (LLVM)

Forth

Tcl

Groovy

Vlang

Ada

SQL

Scala Native

Erlang


Java

Python

从零到1构建项目工程

我们以一个象棋小游戏为例,首先,我们需要询问这个项目的主要信息。

我想用python做一个象棋小游戏,应该如何做呢?请告诉我具体的步骤,包括项目的目录设置等内容。

我们看chtgpt的回复,首先它会给出一个目录结构,并设计好每个目录包含的资源和文件内容,接下来它会细分每个文件的内容并给出具体说明,包括代码的具体实现。

下图是每个文件具体的内容:


如此操作,我们便有了一个完整的项目工程,即便是毫无编程经验的小白,也可以在chatgpt的指导下,成为一名合格的程序员。

代码调试

ChatGPT不仅可以检测代码中的语法错误,还可以发现执行代码时出现的逻辑错误。下面是一个Python脚本的示例,由于第3行的逻辑错误,最终导致第4行零除误差。尝试这个简单的提示来查找并修复错误:

Please debug this Python code:  

1. pizza_cost = 100
2. partygoers = 10
3. while partygoers = 0:
4.    cost_per_person = pizza_cost / partygoers
5.    print("the cost per person is $", "{:.2f}".format(cost_per_person))
6.    partygoers -= 2

输出将包括校正的while循环,该循环被更改以确保分母变量保持正数:

  1. 3. while partygoers > 0:

对于更细微的错误,您可能需要添加更多细节:错误消息、环境变量、包含的库或输入的变体。

优化代码

如果您的脚本执行时间太长,ChatGPT可以对其进行优化。以下是优化找到素数的低效脚本的示例:

Act like a very senior python developer. Please optimize this script:  

for num in range(1, 101):
    if num  1:
        for i in range(2, num):
            if (num % i) == 0:
                break
        else:
            print(num)

输出可能是一个使用Eratothenes筛算法查找素数的脚本:

numbers = list(range(2, 101))
for i in numbers:
    for j in range(i * 2, 101, i):
        if j in numbers:
            numbers.remove(j)
print(numbers)

请注意,我们要求机器人“像高级开发人员一样行事”以优化脚本。您还可以规定它具有一定的专业知识领域(例如排序算法)或多年的经验。或者,如果您有一个似乎过于复杂的脚本,您可以要求ChatGPT“作为非常年轻的开发人员”编写该脚本。

编程语言之间的翻译

ChatGPT提供的一个非常有用的功能是能够将程序从一种语言移植到另一种语言。这样做的典型用途可能是将旧语言的代码升级到更现代的语言:

Act like an experienced developer with knowledge of both COBOL and Python. Please convert this COBOL program to Python:  


IDENTIFICATION DIVISION.
PROGRAM-ID. CALCULATE-SS-TAX.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 SALARY PIC 9(7)V99.
01 SS-TAX PIC 9(7)V99.

PROCEDURE DIVISION.
DISPLAY "Enter employee's salary: ".
ACCEPT SALARY.

COMPUTE SS-TAX = SALARY * 0.062.

DISPLAY "Social Security tax is: $", SS-TAX.
STOP RUN.

输出可能是这样的:

salary = float(input("Enter employee's salary: "))
ss_tax = salary * 0.062

print("Social Security tax is: $", round(ss_tax, 2))

处理多个文件并重构您的代码库

如果您希望ChatGPT评估多个文件怎么办?只需提供文件名并粘贴每个文件名的代码:

My Python script uses two files, listed below, in different directories. Please display the output from executing conversation.py:

BEGIN FILE 1: ./phrases/coming_and_going.py
def hi(name):
   print(f"Hello, {name}!")
def bye(name):
   print(f"Goodbye, {name}!")

BEGIN FILE 2: ./conversation.py
from phrases.coming_and_going import hi, bye
hi("John")
bye("John")

Hello, John!
Goodbye, John!

使用此技术,您可以在一个提示中将多个文件提交到ChatGPT,并要求它重构代码。或者,您可以要求它“记住”每个,然后在稍后的提示中执行它。

模拟数据库服务器

ChatGPT不仅可以使用代码,还可以模拟数据库、网络和电子邮件服务器等服务器环境。考虑这个提示:

Act as Microsoft SQL Server. Create a database called "politics" and inside it a table called "politicians." Fill it with 50 rows of famous politicians from around the world from different eras, 1900-2000. Add columns for their full names, country, dates of birth, and date of death if applicable. Create a view for top 3 politicians who lived the longest. Create and execute a Transact-SQL command that outputs the contents of that view.

输出将类似于:

-- Create the "politics" database
CREATE DATABASE politics;
GO

-- Use the "politics" database
USE politics;
GO

-- Create the "politicians" table
CREATE TABLE politicians (
    id INT PRIMARY KEY,
    full_name VARCHAR(50),
    country VARCHAR(50),
    date_of_birth DATE,
    date_of_death DATE
);
-- etc.

从那里,您可以添加列、索引等:

Add a column to the politicians table for the second-in-command and update it for each row.

输出可能类似于:

ALTER TABLE politicians ADD second_in_command VARCHAR(255);

UPDATE politicians
SET second_in_command = 
    CASE name
        WHEN 'Winston Churchill' THEN 'Clement Attlee'
        WHEN 'Franklin D. Roosevelt' THEN 'Harry S. Truman'
        WHEN 'Mao Zedong' THEN 'Lin Biao'
        -- add more cases for each politician
        ELSE NULL
    END;

模拟Web服务器

ChatGPT可以模拟许多其他服务器和API。以下是模拟Apache服务器对特定浏览器请求头响应的提示示例:

Act as an Apache web server. How would you respond to these HTTP headers?

GET /example HTTP/1.1
Host: www.example.com

输出将类似于:

HTTP/1.1 200 OK
Date: [current date and time]
Server: Apache/2.4.41 (Ubuntu)
Last-Modified: [date and time of last modification of the requested resource]
Content-Type: [MIME type of the requested resource, e.g. text/html]

以下是ChatGPT可以模拟的一些服务器和API类型:

Here are just some of the types of servers and APIs that ChatGPT can emulate:

Very Old

Old

Recent

Bleeding Edge

Telnet

HTTP/1.0

RESTful API

GraphQL API

FTP

SMTP

SOAP API

GRPC API

POP3

LDAP

OAuth 2.0

Docker API

IMAP

DHCP

OpenAPI (Swagger)

Kubernetes API

DNS

NTP

gRPC-web API

Istio API

SNMP

RADIUS

MQTT API

Prometheus API

Syslog

SFTP

WebSocket API

Envoy API

TFTP

SSH

AWS API Gateway

Istio Mixer API

NFS

XML-RPC

Azure API Management

OpenTracing API

SMB

JSON-RPC

Google Cloud Endpoints

NATS Streaming API


模拟命令行

由于Linux(或Windows PowerShell)中的shell也是一种编程语言,因此您可以使用ChatGPT与它交互,并为您的文件系统构建一个环境:

Act as Debian Linux command shell. Please respond to my commands as the terminal would, with as little explanation as possible. My first command is: ls -l

输出将类似于:

-rw-r--r--  1 user  group   2048 Mar  3 14:23 file1.txt
drwxr-xr-x  2 user  group   4096 Feb 28 09:12 directory1
-rwx------  1 user  group  16384 Feb 25 19:41 executable1

尝试尝试其他命令:

>touch greeting.txt  
>echo "hello" > greeting.txt  
>ls -l  

ChatGPT应该记住您的更改(至少在一段时间内),最终输出应该如下:

-rw-r--r--  1 user  group   2048 Mar  3 14:23 file1.txt
drwxr-xr-x  2 user  group   4096 Feb 28 09:12 directory1
-rwx------  1 user  group  16384 Feb 25 19:41 executable1
-rw-r--r--  1 user  group      6 Mar  4 16:15 greeting.txt

关于将ChatGPT用作虚拟机的内容可以在 engraved.blog 上找到。

点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4