
1.2 Python操作入门
1.2.1 编写第一个Python代码
运行PyCharm后,需要先新建计划(Project),单击“Create New Project”选项,如图1-9所示。

图1-9
设置Location(路径)和Interpreter(翻译器),笔者同时安装了Python和Anaconda,所以图1-10中的翻译器有两个可选项,二者的区别在于Anaconda中有许多预置好的库,不用再配置库了。这里选择Python原版的翻译器,然后单击右下角的“Create”按钮。

图1-10
新建计划后,在左侧的项目窗口中右击鼠标,在弹出的快捷菜单中选择“New”g“Python File”命令,新建Python文件(见图1-11)。

图1-11
设置Name(文件名),然后单击右下角的“OK”按钮(见图1-12)。

图1-12
新建Python文件后,右侧的空白区域就是代码编辑区(见图1-13)。
从“Hello,World!”(你好,世界!)开始吧!在代码编辑区中输入“print('Hello, World! ')”,print()是一个打印函数,表示将括号中的文本打印在即时窗口中。然后将鼠标光标停留在括号右侧,右击鼠标,在弹出的快捷菜单中选择“Run 'test'”命令,其中单引号中的test是当前的文件名,一定要注意运行的文件名和要运行的文件名保持一致。运行后可以观察到即时窗口中打印出“Hello,World!”,如图1-14所示。

图1-13

图1-14
1.2.2 Python基本操作
1.Python注释
注释的目的是让阅读者能够轻松读懂每一行代码的意义,同时也为后期代码维护提供便利。在Python中,单行注释以#号开头,如下所示。

Python的多行注释用两个三引号(''')包含起来,如下所示。

2.Python的行缩进
Python最具特色的就是使用缩进来表示代码块,不需要使用大括号。缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数,缩进不一致会导致代码运行错误。
正确缩进的示例如下。

错误缩进的示例如下。

3.多行语句
Python通常是一行写完一条语句,但如果语句很长,则可以通过反斜杠(\)来实现多行语句。

这里的输出结果为“Little Robert asked his mother for two cents.'What did you do with the money I gave you yesterday?'”。
4.等待用户输入
Python中的input()函数是用来与用户进行交互的,如下所示。

此时,运行结果为“Who are you?”。
当用户输入“Lingyi”,然后按【Enter】键时,程序会继续运行,其输出结果如下。

1.2.3 变量
1.变量赋值
在代码编辑区输入以下代码。

注意:Python的变量无须提前声明,赋值的同时也就声明了变量。
2.变量命名
Python中具有自带的关键字(保留字),任何变量名不能与之相同。在Python的标准库中提供了一个keyword模块,可以查阅当前版本的所有关键字,如下所示。
