Python的基础语法

时间:2023-03-09 20:04:24
Python的基础语法

一,编码

默认情况下,Python 3 源码文件以 UTF-8 编码,所有字符串都是 unicode 字符串。 当然你也可以为源码文件指定不同的编码:

1 # -*- coding: cp-1252 -*-

二,标识符

标识符是用于给变量、函数等命名的一串字符串,但是字符串未必是标识符

标识符规则

1.只能由字母,数字,下划线组成,并且不能为数字开头

2.区分大小写,如Fruits和fruits为不同关键字

3.不能为关键字,关键字为python预留,可在Python中用import函数导出:

1 import keyword
2 keyword.kwlist
3 ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', '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']

#在Python3中,非ASCLL标识符也是允许的

三,注释

1.Python中注释以#开头,#后的内容会被Python解释器忽略,如:

1 #这是一行注释
2 print ('Hello,Python!') #这里也是注释

执行代码后,输出结果为:

1 Hello,Python!

2.多行注释,""" 被注释内容 """ 或 ''' 被注释的内容 ''',如:

1 print ('Hello,everyone!')
2 '''
3 这是第一行注释
4 这是第二行注释
5 这是第三行注释
6 '''

执行以上代码输出结果:

Hello,everyone!

四,行与缩进

Python最具色的就是使用缩进来表示代码块,不需要使用大括号({})。

缩进的空格数是可变的,但是同一个代码块的语句必须包含相同的缩进空格数(官方建议缩进4个空格键,不要使用tab键),如:

1 if True:
2 print ('True')
3 else:
4 print ('False')

当代码语句缩进的空格数不一致,会导致运行错误,如:

1 if True:
2 print ('answer')
3 print ('True')
4 else:
5 print ('answer')
6 print ('False') #缩进不一致,会导致运行错误

以上程序由于缩进不一致,执行后会出现类似以下错误:

1 File "<input>", line 6
2 print ('False') #缩进不一致,会导致运行错误
3 ^
4 IndentationError: unindent does not match any outer indentation level

五,多行语句

Python通常是一行写完一条语句,但如果语句过长,我们可以使用反斜杠(\)来实现多行语句,如:

1 total = item_1 + \
2 item_2 + \
3 item_3

在列表[],元祖(),字典{}中的多行语句,不需要使用反斜杠(\),如:

1 total = ['item_1','item_2'
2 'item_3','item_4']

六,数据类型

1.Number数字

整数,浮点数(小数),复数

2.String字符串  https://www.cnblogs.com/weiwenliang/p/10572738.html

3.boolean布尔值(True,False)  https://www.cnblogs.com/weiwenliang/p/10584189.html

4.none空值

5.list列表[]  https://www.cnblogs.com/weiwenliang/p/10583931.html

6.tuple元祖() https://www.cnblogs.com/weiwenliang/p/10584143.html

7.dict字典{} https://www.cnblogs.com/weiwenliang/p/10590297.html

8.set集合()  https://www.cnblogs.com/weiwenliang/p/10590403.html

七,字符串

1.Python中单引号和双引号使用完全相同。

2.使用三引号('''或者""")可以指定一个多行字符串

3.转义符'\'

4.自然字符串,通过在字符串前加r或者R。如r"this is a line with \n"则\n会显示,并不是换行。

5.Python允许处理Unicode字符串,加前缀u或者U,如u"this is an unicode string"。

6.字符串是不可变的。

7.按字面意义级联字符串,如"this""is""string"会被自动转换为this is string。

例如

1 word = '字符串'
2 sentence = "这是一个句子。"
3 paragraph = """这是一个段落,
4 可以由多行组成"""

八,空行

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

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

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

九,输出

print()在括号中加上字符串,就可以向屏幕上输出指定的文字。比如输出'hello, world',用代码实现如下:

1 >>> print ('hello, world')

print()函数也可以接受多个字符串,用逗号“,”隔开,就可以连成一串输出:

1 print ('The quick brown fox', 'jumps over', 'the lazy dog')
2 The quick brown fox jumps over the lazy dog

print()会依次打印每个字符串,遇到逗号“,”会输出一个空格,因此,输出的字符串是这样拼起来的:

Python的基础语法

print()也可以打印整数,或者计算结果:

1 print (300)
2 300
3 print (100 + 200)
4 300

因此,我们可以把100 + 200的结果打印的更漂亮一点:

1 print ('100 + 200 =',100 + 200)
2 100 + 200 = 300

注意,对于100 + 200,Python解释器自动计算出结果300,但是,'100 + 200 ='是字符串而非数学公式,Python把它视为字符串,请自行解释上述打印结果。

print 默认输出是换行的,如果要实现不换行需要在变量末尾加上 end="":

 1 x = 'a'
2 y = 'b'
3 #换行输出
4 print (x)
5 print (y)
6
7 print ('----------')
8 #不换行输出
9 print (x,end = " ")
10 print (y,end = " ")
11 print ()

执行结果为

1 a
2 b
3 ----------
4 a b

十,输入

现在已经可以用print()输出想要的结果了。但是,如果想要让用户能从电脑输入一些字符怎么办?Python提供了一个input()函数,可以让用户输入字符串,并存放到一个变量里,比如输入用户的名字:

1 >>> name = input()
2 weiwenliang

当你输入name = input()并按下回车后,Python交互式命令行就在等待你的输入了。这时你可以输入任意字符,然后按回车完成输入。

输入完成后不会有任何提示,Python交互式命令行又回到>>>状态了。那么我们刚才输入的内容到哪里去了呢?答案是存放到变量name中了,可以直接输入name查看变量值:

1 >>> name
2 'weiwenliang'

十一,同一行显示多条语句

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

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

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

weiwenliang

十二,多个语句构成代码组

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

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

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

1 num = int(input())
2 a = num % 10
3 b = num // 10 % 10
4 c = num // 100
5 if num == a**3 + b**3 + c**3:
6 print ('yes')
7 else:
8 print ('no')

十三,import 与 from...import

在 python 用 import 或者 from...import 来导入相应的模块。

将整个模块(somemodule)导入,格式为: import somemodule

从某个模块中导入某个函数,格式为: from somemodule import somefunction

从某个模块中导入多个函数,格式为: from somemodule import firstfunc, secondfunc, thirdfunc

将某个模块中的全部函数导入,格式为: from somemodule import *

十四,命令行参数

很多程序可以执行一些操作来查看一些基本信息,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 <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, 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.

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