1.  
  2. 主页
  3.  / 
  4. Python基础到高级
  5.  / 
  6. 基础入门

基础入门

第一个 Python 程序

Python的两种编程方式,一是通过Python解释器的交互模式,二是脚本式编程。

首先通过Python交互模式来输出我们的第一个Python程序:

Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello, Python!")
Hello, Python!

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

创建一个文件,使用.py为扩展名。

echo "print("Hello, Python!")" > test.py
python test.py

这样就算是实现了,一个简单的脚本式编程。

Python标识符

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

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

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

以下划线开头的标识符是有特殊意义的。

以单下划线开头 _foo 的代表不能直接访问的类属性,这个不是Python强制定义的,是我们Python开发人员默认觉得要遵守的一个规则,需通过类提供的接口进行访问,不能用 from xxx import * 而导入使用。

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

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

Python 3.7.4 (default, Aug 13 2019, 15:17:50)
[Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print("Hello");print("Python");
Hello
Python

Python 保留字符

下面的列表显示了在Python中的保留字。这些保留字不能用作常量或变量,或任何其他标识符名称。

所有 Python 的关键字只包含小写字母。

andexecnotassertfinallyor
breakforpassclassfromprint
continueglobalraisedefifreturn
delimporttryelifinwhile
elseiswithexceptlambdayield

行和缩进

Python 的代码块和C、Go、或者Java是不相同的,它不使用大括号 {} 来控制类,函数以及其他逻辑判断的开始与结束。

python 最具特色的就是用缩进来写模块。

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

以下实例缩进为四个空格,实例的内容在当前阶段为讲解,无需过多纠结:

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

以下代码将会执行错误,因为未按照标准缩进格式来编写代码:

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

File "", line 5
     print ("False")
                   ^
IndentationError: unindent does not match any outer indentation level

IndentationError: unindent does not match any outer indentation level错误表明,你使用的缩进方式不一致,有的是 tab 键缩进,有的是空格缩进,改为一致即可。

如果是 IndentationError: unexpected indent 错误, 则 python 编译器是在告诉你”Hi,老兄,你的文件里格式不对了,可能是tab和空格没对齐的问题“,所有 python 对格式要求非常严格。

因此,在 Python 的代码块中必须使用相同数目的行首缩进空格数。

建议你在每个缩进层次使用 单个制表符 或 两个空格 或 四个空格 , 切记不能混用

多行语句

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

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

total = item_one + \
        item_two + \
        item_three

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

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

Python 引号

Python 可以使用引号(  )、双引号(  )、三引号( ”’ 或 “”” ) 来表示字符串,引号的开始与结束必须的相同类型的。

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

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

Python注释

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

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

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

name = "Madisetti" # 这是一个注释

python 中多行注释使用三个单引号(”’)或三个双引号(“””)。

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

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

Python空行

函数之间或类的方法之间用空行分隔,表示一段新的代码的开始。

类和函数入口之间也用一行空行分隔,以突出函数入口的开始。

空行与代码缩进不同,空行并不是Python语法的一部分。

书写时不插入空行,Python解释器运行也不会出错。

但是空行的作用在于分隔两段不同功能或含义的代码,便于日后代码的维护或重构。

记住:优秀的代码,空行也是代码的一部分。

输入输出

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

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

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 参数查看各参数帮助信息:

$ python -h
usage: python [option] … [-c cmd | -m mod | file | -] [arg] …
Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .pyc 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
-I     : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O     : remove assert and debug-dependent statements; add .opt-1 before
         .pyc extension; also PYTHONOPTIMIZE=x
-OO    : do -O changes and also discard docstrings; add .opt-2 before
         .pyc extension
-q     : don't print version and copyright messages on interactive startup
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization
-u     : force the stdout and stderr streams to be unbuffered;
         this option has no effect on stdin; also PYTHONUNBUFFERED=x
-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)
         when given twice, print more information about the build
-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
-X opt : set implementation-specific option
--check-hash-based-pycs always|default|never:
    control how Python invalidates hash-based .pyc files
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  directory (or :).
               The default module search path uses /lib/pythonX.X.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', 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.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
   on Python memory allocators. Use PYTHONMALLOC=debug to install debug
   hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
   coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
   locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
   debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.

这篇文章对您有用吗?

我们要如何帮助您?

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注