使用 ChatGPT 協助寫程式

今天的限免課程,有一堂《使用 ChatGPT 更快地學習程式設計》。

Lógica de Programação Aprenda de forma acelerada com ChatGPT

Programming Logic Learn faster with ChatGPT

可能因為該課程是葡萄牙語,上午8:40分享時,註冊人數是728人,一直到上午11點,也才到982人,尚未額滿。


他是在 ChatGPT 中問答一些程式語法範例,來達成學習的目的。

同樣的問題,應用在三種程式語言中:VisualG(巴西當地蠻特殊的,專供程式教學的語法,需搭配應用程式)、C++、Python。

所有的問答,講師整理成一個 pdf 檔(葡萄牙文,google doc 可以直接翻譯成各種語言,我在 ChatGPT 中測試時是用英文),讓大家直接下載。

你可以看 pdf 檔中的答案,也可以自己在 ChatGPT 中輸入問題,看它怎麼回。


我以 Python 第一題為例,示範給大家看:

ChatGPT Q&A

問:Create a Python exercise on Data Input and Output and solve it.

答:(以下是 ChatGPT 的回答,我稍微改了格式,以方便閱讀,但文字內容未變。中文翻譯是 Chrome 翻,一樣故意不修改)

Exercise:

Writing and Reading a CSV File

In this exercise, you will create a Python script that writes some data to a CSV file and then reads that data back in. The script will ask the user for some input and then store that input in a CSV file. It will then read the data from the file and display it to the user.

Read the data from the CSV file and print it to the console.

寫入和讀取 CSV 文件

在本練習中,您將創建一個 Python 腳本,該腳本將一些數據寫入 CSV 文件,然後將這些數據讀回。該腳本將要求用戶提供一些輸入,然後將該輸入存儲在 CSV 文件中。然後它將從文件中讀取數據並將其顯示給用戶。

Instructions:

  1. Ask the user for their name, age, and favorite color.

  2. Write the user’s information to a CSV file named “user_info.csv”. Each line in the file should contain the user’s name, age, and favorite color, separated by commas.

  3. Read the data from the CSV file and print it to the console.

Chrome 翻譯:

  1. 詢問用戶的姓名、年齡和最喜歡的顏色。

  2. 將用戶信息寫入名為“user_info.csv”的 CSV 文件。文件中的每一行都應包含用戶的姓名、年齡和最喜歡的顏色,並以逗號分隔。

  3. 從 CSV 文件中讀取數據並將其打印到控制台。

Example:

Enter your name: Alice
Enter your age: 25
Enter your favorite color: blue

Data saved to user_info.csv

User information:
Name: Alice
Age: 25
Favorite color: blue

Solution:

import csv

# Ask the user for their information
name = input("Enter your name: ")
age = input("Enter your age: ")
favorite_color = input("Enter your favorite color: ")

# Write the data to a CSV file
with open("user_info.csv", "w") as csvfile:
    writer = csv.writer(csvfile)
    writer.writerow([name, age, favorite_color])

print("Data saved to user_info.csv")

# Read the data from the CSV file
with open("user_info.csv", "r") as csvfile:
    reader = csv.reader(csvfile)
    for row in reader:
        name = row[0]
        age = row[1]
        favorite_color = row[2]

# Print the user's information
print("User information:")
print("Name:", name)
print("Age:", age)
print("Favorite color:", favorite_color)

Output:

同 Example。


心得

  1. 我覺得這個問題太發散了,可以有很多答案,詢問時把範圍訂得更明確,才會更符合需求。

  2. 別忘了 ChatGPT 是唬爛王,要記得對產出程式做驗證。

  3. ChatGPT 很適合拿來產出程式範例,不管你要寫文章或教學。

1 的部分,講師 pdf 中的答案,剛好可以拿來做為範例,和我上面得到的答案做比對。

Python Data Input and Output Example:

# Data input
name = input("Enter your name: ") 
age = int(input("Enter your age: "))

# Output data 
print("Name:", name)
print("Age:", age)

VisualG 參考資料

有空時再說明:

3個讚