一. 代码入门第一行
<pre>
"""
第一行只有在linux或unix系统下有作用
调用python脚本时,使用:./script.py
则#!/usr/bin/python 指定解释器的路径
"""
!/usr/bin/python3
print("Helo World")
</pre>
python 3.x要求print加括号(),python2.x则不需要
关于注释行:
通常使用 #注释某一行
使用""" """注释其中整段
使用''' '''在函数中,可以用于在函数的首部对函数进行一个说明
二. 编码说明
默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。
当然你也可以为源码文件指定不同的编码:
···
-- coding: cp-1252 --
···
而在python 2中输出中文,通常会加上:
···
-- coding: UTF-8 --
···
三. python 关键字
···
获取关键字
import keyword
print(keyword.kwlist)
···
得到关键字如下:
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
四. 行与缩进
python使用缩进或者空格来表示代码块。
缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数。实例如下:
···
if True:
print ("True")
else:
print ("False")
···
当语句缩进数的空格数不一致,会导致运行错误:
···
if True:
print ("Answer")
print ("True")
else:
print ("Answer")
print ("False") # 缩进不一致,会导致运行错误
···
执行后会报错如下:
print ("False") # 缩进不一致,会导致运行错误
^
IndentationError: unindent does not match any outer indentation level
这里需要提醒下,大家在复制代码时,有些编辑器会强调空格,我习惯用tab键,所以有时会出现其他形式的报错,以后出现其他错误会再补充。
当在写代码时某一行出现一行代码过长,python提供了 “ \ ”字符,为跨行的代码提供连接,如下:
···
total = item_one +
item_two +
item_three
···
而在[], {}, 或 () 中的多行语句,不需要使用反斜杠(),例如:
···
total = ['item_one', 'item_two', 'item_three',
'item_four', 'item_five']
···