Tutorial

如何写你的第一个Python 3程序

Published on December 2, 2019
中文
如何写你的第一个Python 3程序

简介

“Hello, World!” 程序是一个经典的,确立已久的传统电脑程序。"Hello, World!"因为能展示一个语言的基本句法,因此常被用作初学者的第一个"简单但完整"的程序,并可以被用来测试编程环境。

这个教程将指导你写出第一个Python 3中的"Hello, World"程序。

前提要求

你需要安装好Python 3,并在你的电脑上设置好本地的编程环境。

如果你还没有设置好环境,你可以根据你的操作系统去选择以下之一的Python安装和配置指南:

写"Hello, World!"程序

开始写"Hello, World!",让我们打开一个命令行文本编辑器(比如nano)去创建一个新文件:

  1. nano hello.py

当这个文本文件在命令行窗口打开之后,让我们输入以下程序:

hello.py
print("Hello, World!")

让我们分解这段代码的每个部分,去分步理解。

print()是一个函数,它告诉电脑去执行一个"行动"。我们可以通过"它使用可括号"而知道它是一个函数。print()告诉Python去显示出我们放入括号的任意内容。默认情况下,结果将会打印在当前的命令行窗口之中。

print()类似的一些其它函数,被默认包含在Python语言之中。这些内置函数在写的Python程序中可以随时使用(无需额外步骤去添加)。我们同样可以定义我们自己函数,这需要我们自己通过其它的元素创建。

print()的括号里是一串字符 — Hello, World!。 引号里的任何一串字符都被称作 string(字符串)

当我们写好程序之后,我们可以通过control+x退出nano,在弹出"是否保存文件"选项时点击 y

退出nano后,我们将回到起初的命令行界面。

运行"Hello, World!"程序

我们的"Hello, World!"写好之后,我们就可以准备好去运行它。我们将使用python3命令与文件名一同去运行:

  1. python3 hello.py

我们刚刚创建的hello.py程序将会让你的终端打印出:

Output
Hello, World!

让我们更加详细地回顾,这个程序做了什么。

Python通过 call(调用) print()函数,执行了这一行print("Hello, World!")。字符串的值Hello, World!pass(传递) 到函数之中。

在这个例子中,字符串Hello, World!同样被称作argument(参数),因为它是一个被传入函数的值。

Hello, World!左右两边的引号都没有被打印出来,因为它们被用于告诉Python它们包含着字符串。引号描述了字符串的起始和结束位置。

因为程序成功运行了,我们因此可以确信Python 3已经成功地安装好,并且程序的句法正确。

总结

恭喜你已成功地用Python 3写出了"Hello, World!"程序。

从这里开始,你可以继续使用print()打印出你自己的想显示的字符串,你同样也可以创建新的程序文件。

请通过阅读这个完整的系列教程如何用Python 3编程,去继续学习Python编程。

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors

Default avatar
Gongxia Chen

translator


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel