
3.1 Python编程初识
3.1.1 第一个Python程序
先来看一个经典的示例:

输出结果:

使用一个print()函数将要输出的“Hello World!!!”加上一对单引号即可成功打印需要的文字。需要注意的是,Python与其他语言不同,例如,在C++和Java里单引号只能用于单一的字符,而如果是字符串(或者多个字符),就需要使用双引号,但Python是“通吃”的,即在Python语法里单引号的作用和双引号的是一样的,示例如下:

输出结果:

从输出结果中可以看出,其与使用单引号的效果是一样的。需要注意的是,在输出结果的最后,“Process finished with exit code 0”的意思是“程序运行正常并在结束后收回线程”。当然还可能输出“Process finished with exit code 1”,意思是“程序遇到错误,中止运行”。示例如下:

输出结果:

从输出结果中可以看出,首先显示了发生错误的文件所处的地址,然后输出“SyntaxError:invalid syntax”,意思是“语法错误:非法的语法”,即发现了Python解释器不能理解的语句。还有一种错误是输出Process finished with exit code-1,这一般是在用户自己中断代码运行时出现,例如,使用了Ctrl+Z这种EOF快捷键中断,示例如下:

输出结果:

在运行上述死循环后再中断,得到的返回值为-1。从第1个示例中可以看出,Python的注释形式不同于C++的双斜杠“//”,Python使用井号“#”,而且它不支持C++的“/*…*/”形式的多行注释。Python支持的多行注释的形式是三个单引号“'''”,注意是三个单引号,而不是一个双引号加一个单引号或一个单引号加一个双引号。示例如下:

输出结果:

其中,输出结果的第2行是用户自己输入的,随输入的姓名而变。这里又出现了一个新的函数:input()。它和Python2中的raw_input()函数的作用是一样的。