交互式shell,也称为REPL (Read-Evaluate-Print Loop),是非常好的学习Python的工具。
You’ll remember the things you do much better than the things you only read.
在交互式shell中输入表达式
在Linux下,输入python或python3进入交互式shell,以>>>
作为提示符。
$ python3
Python 3.6.8 (default, Aug 7 2019, 08:02:28)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-39.0.1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> 2 * 5
10
操作符,除了加减乘除用+-*/
表示外,//
表示整除,%
表示余数,**
表示指数。
>>> 26 // 6
4
>>> 26 % 6
2
>>> 2 ** 4
16
整数, 浮点数和字符串数据类型
这3种类型是Python中最基本的数据类型。
字符串类型虽然可以用单引号或双引号包围,但为保持一致性,还是建议单引号:
>>> a="Spring Festival"
>>> a
'Spring Festival'
>>> a='Spring Festival'
>>> a
'Spring Festival'
字符串拼接和复制
拼接用+
,复制用*
。
>>> 'good ' + 'morning'
'good morning'
>>> 'good ' * 5
'good good good good good '
赋值给变量
赋值用=
号,例如variable = expression
,左边必须是变量,右边可以是变量,常数或表达式。
变量在第一次赋值时初始化,后续可被其它类型的表达式覆盖:
>>> a = 'good'
>>> a = 5
变量名是大小写敏感的,a和A是不一样的。命名有两种风格,一种是全小写,然后用_分割,例如station_code
;一种是camelcase
,例如stationCode
。本书作者倾向于后者,而 Python Crash Course
的作者倾向于前者。我个人倾向于前者,无论如何,就像两本书的作者所说,保持一致就好。
作者还挺倔,整了句爱默生Self-Reliance <论自助>里的句子:
A Foolish Consistency Is the Hobgoblin of Little Minds
意思是:愚蠢地坚持随众好比心胸狭小的小妖精
第一个程序
可视化的执行代码可以用Python Tutor。
特定程序的可视化执行可参见这里。https://autbor.com/
中有很多已写好的例子。
解剖你的代码
注释符用#
,所有注释符之后的部分全部忽略,所以#
并不必顶行写。另外,注释符之后的空行全部忽略。
输出用print()
:
>>> print
<built-in function print>
>>> print()
>>> print('Hello, World!')
Hello, World!
>>> a = 'Hello '
>>> b = 'World!'
>>> print(a + b)
Hello World!
输入用input,input的输出是字符串类型:
>>> yourName = input('please input your name: ')
please input your name: Bob
>>> print('your name is ' + yourName)
your name is Bob
字符串长度用len()
,转换数据类型用str()
,int()
或float()
:
>>> age = input('your age:')
your age:18
>>> age
'18'
>>> age + 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> int(age) + 1
19
>>> len(age)
2
>>> int(7.7) # int可以用来取整
7
判断相等用==
:
>>> 12 == '12'
False
>>> 12 == 12.0
True
最后来说说Python的文档,可参考https://docs.python.org/
。例如内置函数可参见这里。
单词
syntactical - 句法的
arcane - 神秘,晦涩难懂的
magic wand - 魔术棒
feat - 武艺,技艺
dissect - 解剖