探索 macOS 12 中的 Python:从安装到绘图

在本文中,我们将探索如何在 macOS 12 系统中打开并使用 Python。这不仅包括安装 Python,还包括编写简单的 Python 脚本,以及使用 Python 绘制饼状图。我们将使用 Markdown 语法来展示代码示例,以及使用 Mermaid 语法来创建饼状图。

安装 Python

macOS 12 系统默认安装了 Python 2.7,但是为了获得最新特性和更好的支持,我们推荐安装 Python 3。可以通过以下两种方式安装 Python 3:

  1. 使用 Homebrew: Homebrew 是 macOS 的包管理器,可以方便地安装 Python 3。首先,打开终端(Terminal)并运行以下命令来安装 Homebrew:

    /bin/bash -c "$(curl -fsSL 
    
    • 1.

    安装完成后,使用 Homebrew 安装 Python 3:

    brew install python3
    
    • 1.
  2. 使用官方安装包: 访问 Python 官方网站下载 macOS 版本的 Python 安装包,然后按照提示进行安装。

验证 Python 安装

安装完成后,可以通过在终端中运行以下命令来验证 Python 是否安装成功:

python3 --version
  • 1.

这将显示安装的 Python 版本。

编写 Python 脚本

现在,让我们编写一个简单的 Python 脚本。首先,打开文本编辑器,例如 TextEdit,然后输入以下代码:

# 这是一个简单的 Python 脚本

def greet(name):
    print(f"Hello, {name}! Welcome to Python.")

greet("World")
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.

保存这个文件为 hello.py。然后,在终端中,导航到该文件所在的目录,并运行以下命令:

python3 hello.py
  • 1.

如果一切顺利,你将在终端中看到输出:Hello, World! Welcome to Python.

使用 Python 绘制饼状图

Python 的 matplotlib 库可以用来绘制各种图表,包括饼状图。首先,确保安装了 matplotlib

pip3 install matplotlib
  • 1.

接下来,我们将编写一个脚本来绘制一个简单的饼状图。创建一个新的 Python 文件,例如 pie_chart.py,并输入以下代码:

import matplotlib.pyplot as plt

# 数据
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0.1, 0, 0, 0)  # 突出显示第一个部分

# 绘制饼状图
plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=140)

plt.axis('equal')  # 确保饼状图是圆形的
plt.title('Pie Chart Example')
plt.show()
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.

运行这个脚本:

python3 pie_chart.py
  • 1.

你将看到一个饼状图,其中包含了四个部分:青蛙、猪、狗和木头。

使用 Mermaid 绘制饼状图

除了使用 Python 绘制饼状图,我们还可以使用 Mermaid 语法在 Markdown 中直接创建饼状图。以下是一个饼状图的 Mermaid 代码示例:

Pie Chart Example 15% 30% 45% 10% Pie Chart Example Frogs Hogs Dogs Logs

结论

在本文中,我们学习了如何在 macOS 12 系统中安装 Python,编写并运行简单的 Python 脚本,以及使用 Python 和 Mermaid 绘制饼状图。Python 是一个功能强大且易于学习的编程语言,适用于从简单的脚本到复杂的应用程序的各种任务。希望本文能帮助你开始你的 Python 之旅,并激发你探索更多的可能性。