Python/创建
维基教科书,自由的教学读本
< Python
欢迎来到 Python!这个教程将教你如何写程序。
Python 源程序代码,只不过是是很多文本文件,可以在简单的文本编辑器上编辑。
Python的节目,只不过是多文本文件,他们可能会修改同一个标准的文本编辑器程序。[1] 您什么{w:文本编辑器|文本编辑器],取决于您的操作系统。任何文本编辑器都可以创建 Python程序,但是有的编辑器有语法加亮功能,这可能会使您更容得编辑。
目录 |
[编辑] Hello, World!
下面是一个在标准输出设备上输出Hello World的简单程序,这种程序通常作为开始学习编程语言时的第一个程序:
print "Hello, world!"
Python 也可以單步直譯執行。執行 Python 直譯器進入互動式命令列的環境,你可以在提示符號 >>> 旁輸入 print "Hello, world!",按 Enter 鍵輸出結果:
print "Hello, world!",
现在,您已经学了 Python 的第一个程序,现在开始尝试编写一个和上面类似的程序吧!
[编辑] Windows
- 使用 Python 创建一个类似于 C:\pythonpractice 的文件夹,然后保存 hello.py 程序到那里。
- 点击开始菜单的 运行 按钮,输入 CMD ,然后按回车,这时会有一个窗口弹出来。
- 输入 cd c:/pythonpractice ,然后按回车。
- 输入 python hello.py 运行您的的程序!
如果 Python 没有正常运行,请您确认路径是否正确。参见 下载和安装
[编辑] Mac
- Create a folder on your computer to use for your Python programs. A good suggestion would be to name it
pythonpracticeand place it in your Home folder (the one that contains folders for Documents, Movies, Music, Pictures, etc). Save yourhello.pyprogram into this folder. - Open the Applications folder, go into the Utilities folder, and open the Terminal program.
- Type
cd ~/pythonpracticeto change directory to yourpythonpracticefolder, and hit Enter. - Type
python hello.pyto run your program!
[编辑] Linux
- 在你的计算机上建立一个文件夹用来存放Python程序,比如
~/pythonpractice,并把hello.py程序存在那里。 - 打开终端程序。在KDE中,打开主菜单并选择"Run Command..." 来打开 Konsole. 在 GNOME中, 打开主菜单,然后是应用程序文件夹,然后打开附件文件夹,选择终端程序。
- 输入
cd ~/pythonpractice并单击回车键,进入到pythonpractice文件夹。 - 输入
python hello.py运行刚刚建立的python程序!
[编辑] 结果
运行完成将输出 "Hello, world!" ,祝贺!您现在已经走上了成为一名 Python 程序员的路。
[编辑] Interactive mode
程序运行完后 Python 将退出,您可以使用 -i 命令去进入互交模式。这非常有用,可以短时间内查找到程序的错误。
python -i hello.py
[编辑] Exercises
- Modify the
hello.pyprogram to say hello to a historical political leader (or to Ada Lovelace). - Change the program so that after the greeting, it asks, "How did you get here?".
- Re-write the original program to use two
printstatements: one for "Hello" and one for "world". The program should still only print out on one line.
[编辑] Notes
- ↑ 有时,Python 会使用分布式汇编的形式,不过这在初学阶段将暂时不会被用到。