Python 编程入门

Python 编程入门

Python 语法简洁易读,广泛用于数据分析、自动化、Web 开发和编程教学。本文将带你编写第一个程序,学习变量、列表、字典、函数以及读取文件。

测试说明:编写本文所用的电脑没有安装 Python,因此代码尚未在此运行。请自行运行每个示例并检查输出。测试完成后,文章会展示真实输出。

需要准备的东西

工作原理

示意图:.py 文件由 Python 解释器运行,并产生输出
示意图:.py 文件由 Python 解释器运行,并产生输出

第一个程序

创建 `hello.py` 并输入:

print("สวัสดี Python")

用 `python hello.py` 运行,应看到 `สวัสดี Python`。

变量与列表

name = "สมชาย"
scores = [85, 72, 45]
average = sum(scores) / len(scores)
print(name, "คะแนนเฉลี่ย", round(average, 2))

Python 不需要声明变量类型。列表保存可变的一组元素,`len` 返回元素个数。

字典与条件

students = {"สมชาย": 85, "สมหญิง": 72, "สมศักดิ์": 45}

def grade(score):
    if score >= 80:
        return "A"
    elif score >= 70:
        return "B"
    elif score >= 50:
        return "C"
    return "F"

for name, score in students.items():
    print(name, grade(score))

字典保存键值对。函数用 `def` 定义,缩进表示代码块。

读写文件

with open("scores.txt", "w", encoding="utf-8") as f:
    f.write("สมชาย,85\nสมหญิง,72\n")

with open("scores.txt", encoding="utf-8") as f:
    for line in f:
        name, score = line.strip().split(",")
        print(name, int(score))

`with` 会自动关闭文件,`encoding="utf-8"` 确保泰语文字正确处理。

常见错误

下一步

编写一个程序,从 `scores.txt` 读取成绩并把结果写入新文件,然后学习 `csv` 和 `datetime` 等标准模块。

总结

Python 的结构清晰易读。列表和字典保存数据,函数组织重复的工作,`with open` 则安全地读写文件。