Python学习--Python基础语法

时间:2023-03-09 19:59:13
Python学习--Python基础语法

第一个Python程序

  交互式编程

  交互式编程不需要创建脚本文件,是通过 Python 解释器的交互模式进来编写代码。

  linux上你只需要在命令行中输入 Python 命令即可启动交互式编程,提示窗口如下:

  Python学习--Python基础语法

  Window上在安装Python时已经已经安装了默认的交互式编程客户端,提示窗口如下:

  Python学习--Python基础语法

  在Python提示符中输入一下文本,然后按回车查看运行结果:

print 'hello world';

  输出:

hello world

  

  脚本式编程

  让我们来写一个简单的Python脚本,所有的Python脚本都要以.py为扩展名,以下是hello.py的内容:

print 'hello python!';

  使用以下命令运行hello.py:

python hello.py

  输出结果:

hello python

Python标识符

在python里,标识符有字母、数字、下划线组成。

在python中,所有标识符可以包括英文、数字以及下划线(_),但不能以数字开头。

python中的标识符是区分大小写的。

以下划线开头的标识符是有特殊意义的。以单下划线开头(_foo)的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用"from xxx import *"而导入;

以双下划线开头的(__foo)代表类的私有成员;以双下划线开头和结尾的(__foo__)代表python里特殊方法专用的标识,如__init__()代表类的构造函数。

行和缩进

  学习Python和其他语言最大的区别在于,Python的代码块不使用({})来控制类、函数以及其他逻辑判断。Python最具特色的就是用缩进来写模块。

  缩进的空白数量是可变的,但是所有的代码块语句必须包含相同的缩进空白数量,这个必须严格执行。

多行语句

  Python语句中一般以新行作为语句的结束符。

  但是我们可以使用(\)将一行的语句分成多行显示,如下:

total = item_one + \
item_two + \
item_three

  语句中包含[],{},()的就不需要使用多行连接符,如下:

number = ['one',
'two',
'three']

Python引号

  Python接受单引号('),双引号("),三引号(''' """)来表示字符串,引号的开始与结束必须是相同类型。

  其中三引号可以由多行组成,编写多行文本的快捷语法,常用语文档字符串,在文件的特定地点,被当做注释。

word = 'word'
sentence = "这是一个句子。"
paragraph = """这是一个段落。
包含了多个语句"""

  

Python注释

  Python中单行注释必须以#开头。

#第一个注释
print "hello Python!" # 第二个注释

  注释可以在语句或表达式行末

user_name = "Tommy" #这是一个注释

  Python中多行注释使用三个单引号('''),或三个双引号(""")。

'''
这是多行注释,使用单引号。
这是多行注释,使用单引号。
''' """
这是多行注释,使用双引号。
这是多行注释,使用双引号。
"""

Python空格

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:空行也是程序代码的一部分。

多个语句构成代码组

缩进相同的一组语句构成一个代码块,我们称之代码组。

像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。

我们将首行及后面的代码组称为一个子句(clause)。

如下:

if expression :
suite
elif expression :
suite
else :
suite

命令行参数

  很多程序可以执行一些操作来查看一些基本信息,Python可以使用-h参数查看各参数帮助信息:

usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-B : don't write .py[co] files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d : debug output from parser; also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also --help)
-i : inspect interactively after running script; forces a prompt even
if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-m mod : run library module as a script (terminates option list)
-O : optimize generated bytecode slightly; also PYTHONOPTIMIZE=x
-OO : remove doc-strings in addition to the -O optimizations
-R : use a pseudo-random salt to make hash() values of various types be
unpredictable between separate invocations of the interpreter, as
a defense against denial-of-service attacks
-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S : don't imply 'import site' on initialization
-t : issue warnings about inconsistent tab usage (-tt: issue errors)
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x
see man page for details on internal buffering relating to '-u'
-v : verbose (trace import statements); also PYTHONVERBOSE=x
can be supplied multiple times to increase verbosity
-V : print the Python version number and exit (also --version)
-W arg : warning control; arg is action:message:category:module:lineno
also PYTHONWARNINGS=arg
-x : skip first line of source, allowing use of non-Unix forms of #!cmd
-3 : warn about Python 3.x incompatibilities that 2to3 cannot trivially fix
file : program read from script file
- : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:] Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH : ';'-separated list of directories prefixed to the
default module search path. The result is sys.path.
PYTHONHOME : alternate <prefix> directory (or <prefix>;<exec_prefix>).
The default module search path uses <prefix>\lib.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONHASHSEED: if this variable is set to 'random', the effect is the same
as specifying the -R option: a random value is used to seed the hashes of
str, bytes and datetime objects. It can also be set to an integer
in the range [0,4294967295] to get hash values with a predictable seed.

  我们在使用脚本形式执行 Python 时,可以接收命令行输入的参数。