Python学习笔记

python是最好的语言.cpp

本篇文章用来记录py基本语法的概览。
可以去菜鸟教程上学习py的语法,菜鸟上有详细且免费的文本教程。

基本语法


标识符

python的标识符命名规则和C++相差无几,略有不同的是,py标识符长度没有限制,但还是以简洁性和区分性为原则。


关键字

py标准库提供了一个keyword模块,可以输出当前版本的所有关键字。

1
2
3
4
import keyword
print(keyword.kwlist)

['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']

注释

py的注释有单行注释#和多行注释'''"""

1
2
3
4
5
6
7
8
9
10
11
12
# 单行注释

'''
多行注释1
多行注释1
'''

"""
多行注释2
多行注释2
"""


行与缩进

py的一大特色就是没有代码块{},而是通过行与缩进来划分代码块。

1
2
3
4
5
if True:
print("Hello, World!")
else:
print("Goodbye, World!")
print("No, bad guy!") #这一行缩进错误,没有else块对齐,也没有和main块(最外界)对齐

多行语句

py的又一大特色就是不以分号;区分语句,一行是一条语句。语句太长怎么办?用反斜杠\来实现转行。

1
2
3
4
5
6
7
8
num1 = num2 = num3 = 1
num4 = num5 = num6 = 2

cnt = num1 + num2 + \
num3 + num4 + \
num5 + num6

print(cnt) #输出9

不过,在[],{},()中,不需要用反斜杠\来区分多行。

1
2
cnt = ['num1', 'num2', 'num3'
'num4', 'num5', 'num6']

Number数字类型

python中有四种类型 :

  • int 整数,如666,默认为长整型
  • bool 布尔,True(或1)、False(或0),注意,首字母必须大写
  • float 浮点数,如1.23,3E-2(E可以小写为e)
  • complex 复数,如1+2j,1.4+2.5j

string字符串类

  • py中单引号'和双引号"完全等价
  • 使用三引号'''"""可以声明一个多行字符串
  • 转义符\可以用来转译。但是字符串前加上r会使转义失效,例如r"is a\n"里的\n会被显式输出,没有换行
  • 字面值自动连接,相邻字符串会自动合并 ‘st’ “rin” ‘g’ 会合并为"string"
  • 字符串用+拼接,如'78'+'34'就是"7834";字符串用*重复,如"iaa"*2就是"iaaiaa"
  • 字符串有两种索引方式,从左往右以0开始,从右往左以-1开始
  • py中的字符串不能改变
  • py没有C/C++中的char类型,一个字符就是长度为1的字符串
  • 字符串切片str[start:end],左闭右开,其中start是切片开始的索引,从0开始计数,end是切片结束的索引
  • 字符串切片可以加上步长参数step,语法格式如下:str[start:end:step]
1
2
3
s1 = '123456789'
print(s1[::2])
#输出13579

同一行显示多条语句

在py中可以用分号;将多条语句放在同一行。

我就说吧,py是C++的远房亲戚

多个语句构成代码组

缩进相同的一组语句构成一个代码块,我们称之为代码组
对于if、while、def、class这样的复合语句,首行以关键字开始,以冒号 : 结束,之后的一行或多行构成一个代码组。
首行以及后面的代码组成为一个子句

print输出默认是换行的,如果不想换行,则在末尾加上,end = ""

1
2
3
print("Hello", end=", ")
print("World")
#输出Hello, World

import与from…import

py用import和from…import来导入模块。

  • 将整个模块’module’导入,格式为: import module
  • 从某个模块中导入某个函数,格式为:from module import function
  • 从某个模块中导入多个函数,格式为:from module import function1, fuction2, fuction3
  • 将某个模块中的全部函数导入,格式为:from module import *

命令行参数

py可以使用-h参数查看个参数帮助信息
以下是示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
E:\Hello World\PyLearning>python -h
usage: python [option] ... [-c cmd | -m mod | file | -] [arg] ...
Options (and corresponding environment variables):
-b : issue warnings about converting bytes/bytearray to str and comparing
bytes/bytearray with str or bytes with int. (-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 : turn on parser debugging output (for experts only, only works on
debug builds); also PYTHONDEBUG=x
-E : ignore PYTHON* environment variables (such as PYTHONPATH)
-h : print this help message and exit (also -? or --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
-P : don't prepend a potentially unsafe path to sys.path; also
PYTHONSAFEPATH
-q : don't print version and copyright messages on interactive startup
-s : don't add user site directory to sys.path; also PYTHONNOUSERSITE=x
-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
--help-env: print help about Python environment variables and exit
--help-xoptions: print help about implementation-specific -X options and exit
--help-all: print complete help information and exit

Arguments:
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:]