Python基础(一)

python基础语法(python2.x)

一、第一个Python程序

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

print ("hello world")

运行效果

hello world

二、中文编码

前面我们已经学会了如何用 Python 输出 "hello world",英文没有问题,但是如果你输出中文字符 "你好,世界" 就有可能会碰到中文编码问题

Python 文件中如果未指定编码,在执行过程会出现报错:

print ("你好,世界")

运行效果

  File "D:/python27/hello.py", line 6
SyntaxError: Non-ASCII character '\xe4' in file D:/python27/hello.py on line 6, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。
解决方法为只要在文件开头加入 # -*- coding: UTF-8 -*- 或者 # coding=utf-8 就行了
注意:Python3.X 源码文件默认使用utf-8编码,所以可以正常解析中文,无需指定 UTF-8 编码。

三、脚本式编程

通过脚本参数调用解释器开始执行脚本,直到脚本执行完毕。当脚本执行完成后,解释器不再有效。

让我们写一个简单的 Python 脚本程序。所有 Python 文件将以 .py 为扩展名。将以下的源代码拷贝至 hello.py 文件中。

print ("Hello, Python!")

这里,假设你已经在windows系统中设置了 Python 解释器 PATH 变量。进入py文件所在目录,Windows+R键进入cmd进入命令窗口,使用以下命令运行程序:

python hello.py

运行效果

Hello, Python!

四、Python2.x 中使用 Python3.x 的 print 函数

如果 Python2.x 版本想使用使用 Python3.x 的 print 函数,可以导入 future 包,该包禁用 Python2.x 的 print 语句,采用 Python3.x 的 print 函数:

python2.x 的 print 语句

list =["a", "b", "c"]
print list

运行结果

['a', 'b', 'c']

导入 future

from __future__ import print_function
print list     

Python2.x 的 print 语句被禁用,使用报错,运行效果:

  File "<stdin>", line 1
    print list
             ^
SyntaxError: invalid syntax

使用 Python3.x 的 print 函数

print (list)

运行效果
['a', 'b', 'c']

注意:Python3.x 与 Python2.x 的许多兼容性设计的功能可以通过 future 这个包来导入。

五、Python 标识符

在 Python 里,标识符由字母、数字、下划线组成。
在 Python 中,所有标识符可以包括英文、数字以及下划线(_),但不能以数字开头。
Python 中的标识符是区分大小写的。
以下划线开头的标识符是有特殊意义的。以单下划线开头 _foo 的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx import * 而导入。
以双下划线开头的 __foo 代表类的私有成员,以双下划线开头和结尾的 foo 代表 Python 里特殊方法专用的标识,如 init() 代表类的构造函数。

Python 可以同一行显示多条语句,方法是用分号 ; 分开,如:

print ('hello');print ('runoob');

运行效果

hello
runoob

六、Python 保留字符

在Python中的保留字。这些保留字不能用作常数或变数,或任何其他标识符名称。
所有 Python 的关键字只包含小写字母。

andexecnot
assertfinallyor
breakforpass
classfromprint
continueglobalraise
defifreturn
delimporttry
elifinwhile
elseiswith
exceptlambdayield

七、行和缩进

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

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

if True:
    print ("True")
else:
    print ("False")

以下代码将会执行错误:

# 文件名:test.py

if True:
    print ("Answer")
    print ("True")
else:
    print ("Answer")
    # 没有严格缩进,在执行时会报错
  print ("False")

运行效果

D:\python27\venv\Scripts\python.exe D:/python27/hello.py
  File "D:/python27/hello.py", line 19
    print ("False")
                  ^
IndentationError: unindent does not match any outer indentation level

八、多行语句

Python语句中一般以新行作为语句的结束符。
但是我们可以使用斜杠( \)将一行的语句分为多行显示,如下所示:

total = item_one + \
        item_two + \
        item_three

语句中包含 [], {} 或 () 括号就不需要使用多行连接符。如下实例:

days = ['Monday', 'Tuesday', 'Wednesday',
        'Thursday', 'Friday']

九、Python 引号

Python 可以使用引号( ' )、双引号( " )、三引号( ''' 或 """ ) 来表示字符串,引号的开始与结束必须是相同类型的。
其中三引号可以由多行组成,编写多行文本的快捷语法,常用于文档字符串,在文件的特定地点,被当做注释。

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

十、Python注释

python中单行注释采用 # 开头。

  # 文件名:test.py

  # 第一个注释
  print ("Hello, Python!")  # 第二个注释

运行效果:

Hello, Python!

注释可以在语句或表达式行末:
name = "Madisetti" # 这是一个注释

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

十一、Python空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。类和函数入口之间也用一行空行分隔,以突出函数入口的开始。
空行与代码缩进不同,空行并不是Python语法的一部分。书写时不插入空行,Python解释器运行也不会出错。但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构
记住:空行也是程序代码的一部分。

十二、等待用户输入

下面的程序执行后就会等待用户输入,按回车键后就会退出:

raw_input("按下 enter 键退出,其他任意键显示...\n")

以上代码中 ,\n 实现换行。一旦用户按下 enter(回车) 键退出,其它键显示。

十三、同一行显示多条语句

Python可以在同一行中使用多条语句,语句之间使用分号(;)分割,以下是一个简单的实例:

import sys; x = 'runoob'; sys.stdout.write(x + '\n')

执行以上代码,输入结果为:
runoob

十三、print 输出

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上逗号 ,。


x="a"
y="b"
# 换行输出
print x
print y

print '---------'
# 不换行输出
print x,
print y,

# 不换行输出
print x,y

运行效果:

a
b
---------
a b a b

十五、多个语句构成代码组

缩进相同的一组语句构成一个代码块,我们称之代码组。
像if、while、def和class这样的复合语句,首行以关键字开始,以冒号( : )结束,该行之后的一行或多行代码构成代码组。
我们将首行及后面的代码组称为一个子句(clause)。
如下实例:

if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite

十六、命令行参数

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

  • windows系统
D:\python27>python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options and arguments (and corresponding environment variables):
-b     : issue warnings about comparing bytearray with unicode
         (-bb: issue errors)
-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:]

[省略]
  • linux系统
$ python -h 
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ... 
Options and arguments (and corresponding environment variables): 
-c cmd : program passed in as string (terminates option list) 
-d     : debug output from parser (also PYTHONDEBUG=x) 
-E     : ignore environment variables (such as PYTHONPATH) 
-h     : print this help message and exit 
 
[ etc. ] 

参考来源:菜鸟教程

posted @ 2021-07-06 15:11  Jsonring  阅读(47)  评论(0编辑  收藏  举报
分享到: