2、运行.py文件、字符串、保留字符、行和缩进、多行语句、引号、注释、等待用户输入、同一行显示多条语句、命令行参数

2Python基础语法

2.1运行.py文件

运行方式类似:

$ python test.py

2.2Python标识符

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

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

  • 以下划线开头的标识符是有特殊意义的。以单下划线开头 _foo 的代表不能直接访问的类属性,需通过类提供的接口进行访问,不能用 from xxx import * 而导入。
  • 以双下划线开头的__foo代表类的私有成员,以双下划线开头和结尾的__foo__代表Python里特殊方法专用的标识,如__init__()代表类的构造函数。
  • Python 可以同一行显示多条语句,方法是用分号 ; 分开

2.3Python保留字符

下面的列表现实和了在Python的保留字。这些保留字不能用作常数或变数,或任何其它标识符名称。

and    exec     not       assert    finally    or    break    for     pass    class
from   print     continue   global    raise     def   if     return   del    import
try  elif    in    while     else      is        with    except    lambda   yield

2.4行和缩进

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

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

以下实例缩进为四个空格:

# -*- coding: UTF-8 -*-

if True:
    print("Answer")
    print("True")
else:
    print("Answer")
    #没有严格缩进,在执行时会报错(下面的代码有严格缩进,所以不会报错)
    print("False")

运行结果:

D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文编码/02_行和缩进.py
Answer
True

以下代码将会执行错误:

# -*- coding: UTF-8 -*-

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

执行结果:

D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文编码/02_行和缩进.py
  File "E:/workspace/python/python/01_Python中文编码/02_行和缩进.py", line 9
    print("False")
                 ^
IndentationError: unindent does not match any outer indentation level

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

扫描二维码关注公众号,回复: 8557934 查看本文章

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

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

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

2.5多行语句

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

total = item_one + \
        item_two + \
        item_three

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

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

2.6Python引号

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

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

# -*- coding: UTF-8 -*-

"""
下面是三种引号的写法
"""
word = 'word'
sentence = "设置一个句子"
paragraph = """这是一个段落。
包含了多个语句
"""

print("word = ",word)
print("sentence = " + sentence)
print("paragraph = "+paragraph)

运行结果:

D:\installed\Anaconda3\python.exe E:/workspace/python/python/01_Python中文编码/03_python引号.py
word =  word
sentence = 设置一个句子
paragraph = 这是一个段落。
包含了多个语句


Process finished with exit code 0

2.7Python注释

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

# -*- coding: UTF-8 -*-

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

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

实例:

# -*- coding: UTF-8 -*-

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

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

2.8等待用户输入

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

# -*- coding: UTF-8 -*-

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

运行结果:

D:\installed\Anaconda3\python.exe E:/workspace/python/python/Python/06_等待用户输入.py
按下enter键退出,其他任意键显示...


Process finished with exit code 0

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

2.9同一行显示多条语句

# -*- coding: UTF-8 -*-

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

输出结果:

D:\installed\Anaconda3\python.exe E:/workspace/python/python/Python/07_同一行显示多条语句.py
runoob

Process finished with exit code 0

2.10多个语句构成代码组

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

如下实例:

if expression : 
   suite 
elif expression :  
   suite  
else :  
   suite 

2.11命令行参数

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

C:\Users\toto>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 <prefix> directory (or <prefix>;<exec_prefix>).
               The default module search path uses <prefix>\python{major}{minor}.
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 and bytes 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.
PYTHONPYCACHEPREFIX: root directory for bytecode cache (pyc) files.

C:\Users\toto>
发布了1047 篇原创文章 · 获赞 328 · 访问量 385万+

猜你喜欢

转载自blog.csdn.net/toto1297488504/article/details/103553655