Python 程序的开始通常包括以下部分:
编码声明
-*- coding: utf-8 -*-
这行代码告诉 Python 解释器源代码的编码是 UTF-8。
shebang 行(可选):
!/usr/bin/env python
这行代码指定了解释器路径,使用 `!/usr/bin/env python` 可以让系统在环境变量中查找 Python 解释器,这样如果 Python 解释器不在 `/usr/bin/python` 中,程序仍然可以运行。
导入模块(可选):
import sys
如果程序需要使用外部模块,可以在这里导入。
定义函数或类(可选):
def hello_world():
print("Hello, World!")
如果程序中包含函数或类的定义,可以在这里开始。
主程序入口(如果适用):
if __name__ == "__main__":
hello_world()
这行代码确保只有在直接运行脚本时才会执行 `hello_world` 函数。
一个简单的 Python 程序示例可能如下所示:
-*- coding: utf-8 -*-
!/usr/bin/env python
def hello_world():
print("Hello, World!")
if __name__ == "__main__":
hello_world()
请确保在保存文件时,文件名以 `.py` 结尾,并在命令行中使用 `python 文件名.py` 来运行程序。