python入门

1. 注释 在 Python 中,# 表示注释,作用于整行。 【例子】单行注释

这是一个注释

print(“Hello world”)

Hello world

Hello world
‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释

‘’’
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
‘’’
print(“Hello china”)

Hello china


“”"
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
“”"
print(“hello china”)

hello china

Hello china
hello china
2. 运算符
算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例子】

print(1 + 1) # 2
print(2 - 1) # 1
print(3 * 4) # 12
print(3 / 4) # 0.75
print(3 // 4) # 0
print(3 % 4) # 3
print(2 ** 3) # 8
2
1
12
0.75
0
3
8
比较运算符

操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

print(2 > 1) # True
print(2 >= 4) # False
print(1 < 2) # True
print(5 <= 2) # False
print(3 == 4) # False
print(3 != 5) # True
True
False
True
False
False
True
逻辑运算符

操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

print((3 > 2) and (3 < 5)) # True
print((1 > 3) or (9 < 2)) # False
print(not (2 > 1)) # False
True
False
False
位运算符

操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
按位或
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】有关二进制的运算,参见“位运算”部分的讲解。

print(bin(4)) # 0b100
print(bin(5)) # 0b101
print(bin(~4), ~4) # -0b101 -5
print(bin(4 & 5), 4 & 5) # 0b100 4
print(bin(4 | 5), 4 | 5) # 0b101 5
print(bin(4 ^ 5), 4 ^ 5) # 0b1 1
print(bin(4 << 2), 4 << 2) # 0b10000 16
print(bin(4 >> 2), 4 >> 2) # 0b1 1
0b100
0b101
-0b101 -5
0b100 4
0b101 5
0b1 1
0b10000 16
0b1 1
三元运算符

【例子】

x, y = 4, 5
if x < y:
small = x
else:
small = y

print(small) # 4
4
有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

【例子】

x, y = 4, 5
small = x if x < y else y
print(small) # 4
4
其他运算符

操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
not is 不是 “hello” is not “hello”
【例子】

letters = [‘A’, ‘B’, ‘C’]
if ‘A’ in letters:
print(‘A’ + ’ exists’)
if ‘h’ not in letters:
print(‘h’ + ’ not exists’)

A exists

h not exists

A exists
h not exists
【例子】比较的两个变量均指向不可变类型。

a = “hello”
b = “hello”
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
True True
False False
【例子】比较的两个变量均指向可变类型。

a = [“hello”]
b = [“hello”]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
False True
True False
注意:

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级

一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)。
先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 1 << (3 + 2)) & 7。
逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)。
【例子】

print(-3 ** 2) # -9
print(3 ** -2) # 0.1111111111111111
print(1 << 3 + 2 & 7) # 0
print(-3 * 2 + 5 / -2 - 4) # -12.5
print(3 < 4 and 4 < 5) # True
-9
0.1111111111111111
0
-12.5
True
3. 变量和赋值
在使用变量之前,需要对其先赋值。
变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
Python 变量名是大小写敏感的,foo != Foo。
【例子】

teacher = “老马的程序人生”
print(teacher) # 老马的程序人生
老马的程序人生
【例子】

first = 2
second = 3
third = first + second
print(third) # 5
5
【例子】

myTeacher = “老马的程序人生”
yourTeacher = “小马的程序人生”
ourTeacher = myTeacher + ‘,’ + yourTeacher
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
4. 数据类型与转换
类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False
整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是int。

a = 1031
print(a, type(a))

1031 <class ‘int’>

1031 <class ‘int’>

Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。

【例子】

b = dir(int)
print(b)

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’,

delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’,

float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’,

getattribute’, ‘getnewargs’, ‘gt’, ‘hash’,

index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’,

le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’,

neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,

rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’,

rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’,

round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’,

rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’,

sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’,

‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’,

‘numerator’, ‘real’, ‘to_bytes’]

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’, ‘delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’, ‘float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’, ‘getattribute’, ‘getnewargs’, ‘gt’, ‘hash’, ‘index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’, ‘le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’, ‘neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’, ‘rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’, ‘round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’, ‘rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’, ‘sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]
对它们有个大概印象就可以了,具体怎么用,需要哪些参数 (argument),还需要查文档。看个bit_length()的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

a = 1031
print(bin(a)) # 0b10000000111
print(a.bit_length()) # 11
0b10000000111
11
浮点型

【例子】

print(1, type(1))

1 <class ‘int’>


print(1., type(1.))

1.0 <class ‘float’>


a = 0.00000023
b = 2.3e-7
print(a) # 2.3e-07
print(b) # 2.3e-07
1 <class ‘int’>
1.0 <class ‘float’>
2.3e-07
2.3e-07
有时候我们想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现。

import decimal
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

a = decimal.getcontext()
print(a)

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

capitals=1, clamp=0, flags=[],

traps=[InvalidOperation, DivisionByZero, Overflow])

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)
print(b)

0.3333333333333333333333333333

0.3333333333333333333333333333
【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print©

0.3333

0.3333
布尔型

布尔 (boolean) 型变量只能取两个值,True 和 False。当把布尔型变量用在数字运算中,用 1 和 0 代表 True 和 False。

【例子】

print(True + True) # 2
print(True + False) # 1
print(True * False) # 0
2
1
0
除了直接给变量赋值 True 和 False,还可以用 bool(X) 来创建变量,其中 X 可以是

基本类型:整型、浮点型、布尔型
容器类型:字符串、元组、列表、字典和集合
【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是 False。

print(type(0), bool(0), bool(1))

<class ‘int’> False True


print(type(10.31), bool(0.00), bool(10.31))

<class ‘float’> False True


print(type(True), bool(False), bool(True))

<class ‘bool’> False True

<class ‘int’> False True
<class ‘float’> False True
<class ‘bool’> False True
【例子】bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

print(type(’’), bool(’’), bool(‘python’))

<class ‘str’> False True


print(type(()), bool(()), bool((10,)))

<class ‘tuple’> False True


print(type([]), bool([]), bool([1, 2]))

<class ‘list’> False True


print(type({}), bool({}), bool({‘a’: 1, ‘b’: 2}))

<class ‘dict’> False True


print(type(set()), bool(set()), bool({1, 2}))

<class ‘set’> False True

<class ‘str’> False True
<class ‘tuple’> False True
<class ‘list’> False True
<class ‘dict’> False True
<class ‘set’> False True
确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。
对于容器变量,里面没元素就是空的。
获取类型信息

获取类型信息 type(object)
【例子】

print(isinstance(1, int)) # True
print(isinstance(5.2, float)) # True
print(isinstance(True, bool)) # True
print(isinstance(‘5.2’, str)) # True
True
True
True
True
注:

type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。

类型转换

转换为整型 int(x, base=10)
转换为字符串 str(object=’’)
转换为浮点型 float(x)
【例子】

print(int(‘520’)) # 520
print(int(520.52)) # 520
print(float(‘520.52’)) # 520.52
print(float(520)) # 520.0
print(str(10 + 10)) # 20
print(str(10.1 + 5.2)) # 15.3
520
520
520.52
520.0
20
15.3
5. print() 函数
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
关键字参数end是输出结束时的字符,默认是换行符\n;
关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
关键字参数flush是立即把内容输出到流文件,不作缓存。
【例子】没有参数时,每次输出后都会换行。

shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(“This is printed without 'end’and ‘sep’.”)
for item in shoplist:
print(item)

This is printed without 'end’and ‘sep’.

apple

mango

carrot

banana

This is printed without 'end’and ‘sep’.
apple
mango
carrot
banana
【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(“This is printed with ‘end=’&’’.”)
for item in shoplist:
print(item, end=’&’)
print(‘hello world’)

This is printed with ‘end=’&’’.

apple&mango&carrot&banana&hello world

This is printed with ‘end=’&’’.
apple&mango&carrot&banana&hello world
【例子】item值与’another string’两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。

shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(“This is printed with ‘sep=’&’’.”)
for item in shoplist:
print(item, ‘another string’, sep=’&’)

This is printed with ‘sep=’&’’.

apple&another string

mango&another string

carrot&another string

banana&another string

This is printed with ‘sep=’&’’.
apple&another string
mango&another string
carrot&another string
banana&another string
位运算

  1. 原码、反码和补码
    二进制有三种不同的表示形式:原码、反码和补码,计算机内部使用补码来表示。

原码:就是其二进制表示(注意,有一位符号位)。

00 00 00 11 -> 3
10 00 00 11 -> -3
反码:正数的反码就是原码,负数的反码是符号位不变,其余位取反(对应正数按位取反)。

00 00 00 11 -> 3
11 11 11 00 -> -3
补码:正数的补码就是原码,负数的补码是反码+1。

00 00 00 11 -> 3
11 11 11 01 -> -3
符号位:最高位为符号位,0表示正数,1表示负数。在位运算中符号位也参与运算。

  1. 按位运算
    按位非操作 ~
    ~ 1 = 0
    ~ 0 = 1
    ~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

00 00 01 01 -> 5
~

11 11 10 10 -> -6

11 11 10 11 -> -5
~

00 00 01 00 -> 4
按位与操作 &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
只有两个对应位都为 1 时才为 1

00 00 01 01 -> 5
&
00 00 01 10 -> 6

00 00 01 00 -> 4
按位或操作 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
只要两个对应位中有一个 1 时就为 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6

00 00 01 11 -> 7
按位异或操作 ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
只有两个对应位不同时才为 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
异或操作的性质:满足交换律和结合律

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

ABA: = AAB = B = 00 00 01 11
按位左移操作 <<
num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3

01 01 10 00 -> 88
按位右移操作 >>
num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2

00 00 00 10 -> 2
3. 利用位运算实现快速计算
通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n
(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b
通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5

00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14

00 00 00 10 -> 2
4. 利用位运算实现整数集合
一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:

a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
集合之间的操作:

a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

【例子】C#语言输出负数。

class Program
{
static void Main(string[] args)
{
string s1 = Convert.ToString(-3, 2);
Console.WriteLine(s1);
// 11111111111111111111111111111101

    string s2 = Convert.ToString(-3, 16);
    Console.WriteLine(s2); 
    // fffffffd
}

}
【例子】 Python 的bin() 输出。

print(bin(3)) # 0b11
print(bin(-3)) # -0b11

print(bin(-3 & 0xffffffff))

0b11111111111111111111111111111101


print(bin(0xfffffffd))

0b11111111111111111111111111111101


print(0xfffffffd) # 4294967293
0b11
-0b11
0b11111111111111111111111111111101
0b11111111111111111111111111111101
4294967293
是不是很颠覆认知,我们从结果可以看出:

Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。这里写自定义目录标题)

欢迎使用Markdown编辑器

你好! 这是你第一次使用 Markdown编辑器 所展示的欢迎页。如果你想学习如何使用Markdown编辑器, 可以仔细阅读这篇文章,了解一下Markdown的基本语法知识。

新的改变

我们对Markdown编辑器进行了一些功能拓展与语法支持,除了标准的Markdown编辑器功能,我们增加了如下几点新功能,帮助你用它写博客:

  1. 全新的界面设计 ,将会带来全新的写作体验;
  2. 在创作中心设置你喜爱的代码高亮样式,Markdown 将代码片显示选择的高亮样式 进行展示;
  3. 增加了 图片拖拽 功能,你可以将本地的图片直接拖拽到编辑区域直接展示;
  4. 全新的 KaTeX数学公式 语法;
  5. 增加了支持甘特图的mermaid语法1 功能;
  6. 增加了 多屏幕编辑 Markdown文章功能;
  7. 增加了 焦点写作模式、预览模式、简洁写作模式、左右区域同步滚轮设置 等功能,功能按钮位于编辑区域与预览区域中间;
  8. 增加了 检查列表 功能。

功能快捷键

撤销:Ctrl/Command + Z
重做:Ctrl/Command + Y
加粗:Ctrl/Command + B
斜体:Ctrl/Command + I
标题:Ctrl/Command + Shift + H
无序列表:Ctrl/Command + Shift + U
有序列表:Ctrl/Command + Shift + O
检查列表:Ctrl/Command + Shift + C
插入代码:Ctrl/Command + Shift + K
插入链接:Ctrl/Command + Shift + L
插入图片:Ctrl/Command + Shift + G
查找:Ctrl/Command + F
替换:Ctrl/Command + G

合理的创建标题,有助于目录的生成

直接输入1次#,并按下space后,将生成1级标题。
输入2次#,并按下space后,将生成2级标题。
以此类推,我们支持6级标题。有助于使用TOC语法后生成一个完美的目录。

如何改变文本的样式

强调文本 强调文本

加粗文本 加粗文本

标记文本

删除文本

引用文本

H2O is是液体。

210 运算结果是 1024.

插入链接与图片

图片: Alt

带尺寸的图片: Alt

居中的图片: Alt

居中并且带尺寸的图片: Alt

当然,我们为了让用户更加便捷,我们增加了图片拖拽功能。

如何插入一段漂亮的代码片

博客设置页面,选择一款你喜欢的代码片高亮样式,下面展示同样高亮的 代码片.

// An highlighted block
var foo = 'bar';

生成一个适合你的列表

  • 项目
    • 项目
      • 项目
  1. 项目1
  2. 项目2
  3. 项目3
  • 计划任务
  • 完成任务

创建一个表格

一个简单的表格是这么创建的:

项目Value
电脑$1600
手机$12
导管$1

设定内容居中、居左、居右

使用:---------:居中
使用:----------居左
使用----------:居右

第一列第二列第三列
第一列文本居中第二列文本居右第三列文本居左

SmartyPants

SmartyPants将ASCII标点字符转换为“智能”印刷标点HTML实体。例如:

TYPEASCIIHTML
Single backticks'Isn't this fun?'‘Isn’t this fun?’
Quotes"Isn't this fun?"“Isn’t this fun?”
Dashes-- is en-dash, --- is em-dash– is en-dash, — is em-dash

创建一个自定义列表

Markdown
Text-to- HTML conversion tool
Authors
John
Luke

如何创建一个注脚

一个具有注脚的文本。2

注释也是必不可少的

Markdown将文本转换为 HTML

KaTeX数学公式

您可以使用渲染LaTeX数学表达式 KaTeX:

Gamma公式展示 Γ ( n ) = ( n − 1 ) ! ∀ n ∈ N \Gamma(n) = (n-1)!\quad\forall n\in\mathbb N Γ(n)=(n1)!nN 是通过欧拉积分

Γ ( z ) = ∫ 0 ∞ t z − 1 e − t d t   . \Gamma(z) = \int_0^\infty t^{z-1}e^{-t}dt\,. Γ(z)=0tz1etdt.

你可以找到更多关于的信息 LaTeX 数学表达式here.

新的甘特图功能,丰富你的文章

Mon 06 Mon 13 Mon 20 已完成 进行中 计划一 计划二 现有任务 Adding GANTT diagram functionality to mermaid
  • 关于 甘特图 语法,参考 这儿,

UML 图表

可以使用UML图表进行渲染。 Mermaid. 例如下面产生的一个序列图:

张三 李四 王五 你好!李四, 最近怎么样? 你最近怎么样,王五? 我很好,谢谢! 我很好,谢谢! 李四想了很长时间, 文字太长了 不适合放在一行. 打量着王五... 很好... 王五, 你怎么样? 张三 李四 王五

这将产生一个流程图。:

链接
长方形
圆角长方形
菱形
  • 关于 Mermaid 语法,参考 这儿,

FLowchart流程图

我们依旧会支持flowchart的流程图:

Created with Raphaël 2.2.0 开始 我的操作 确认? 结束 yes no
  • 关于 Flowchart流程图 语法,参考 这儿.

导出与导入

导出

如果你想尝试使用此编辑器, 你可以在此篇文章任意编辑。当你完成了一篇文章的写作, 在上方工具栏找到 文章导出 ,生成一个.md文件或者.html文件进行本地保存。

导入

如果你想加载一篇你写过的.md文件,在上方工具栏可以选择导入功能进行对应扩展名的文件导入,
继续你的创作。

  1. 注释
    在 Python 中,# 表示注释,作用于整行。
    【例子】单行注释

这是一个注释

print(“Hello world”)

Hello world

Hello world
‘’’ ‘’’ 或者 “”" “”" 表示区间注释,在三引号之间的所有内容被注释
【例子】多行注释

‘’’
这是多行注释,用三个单引号
这是多行注释,用三个单引号
这是多行注释,用三个单引号
‘’’
print(“Hello china”)

Hello china


“”"
这是多行注释,用三个双引号
这是多行注释,用三个双引号
这是多行注释,用三个双引号
“”"
print(“hello china”)

hello china

Hello china
hello china
2. 运算符
算术运算符

操作符 名称 示例

  • 加 1 + 1
  • 减 2 - 1
  • 乘 3 * 4
    / 除 3 / 4
    // 整除(地板除) 3 // 4
    % 取余 3 % 4
    ** 幂 2 ** 3
    【例子】

print(1 + 1) # 2
print(2 - 1) # 1
print(3 * 4) # 12
print(3 / 4) # 0.75
print(3 // 4) # 0
print(3 % 4) # 3
print(2 ** 3) # 8
2
1
12
0.75
0
3
8
比较运算符

操作符 名称 示例

大于 2 > 1
= 大于等于 2 >= 4
< 小于 1 < 2
<= 小于等于 5 <= 2
== 等于 3 == 4
!= 不等于 3 != 5
【例子】

print(2 > 1) # True
print(2 >= 4) # False
print(1 < 2) # True
print(5 <= 2) # False
print(3 == 4) # False
print(3 != 5) # True
True
False
True
False
False
True
逻辑运算符

操作符 名称 示例
and 与 (3 > 2) and (3 < 5)
or 或 (1 > 3) or (9 < 2)
not 非 not (2 > 1)
【例子】

print((3 > 2) and (3 < 5)) # True
print((1 > 3) or (9 < 2)) # False
print(not (2 > 1)) # False
True
False
False
位运算符

操作符 名称 示例
按位取反 ~4
& 按位与 4 & 5
按位或
^ 按位异或 4 ^ 5
<< 左移 4 << 2

右移 4 >> 2
【例子】有关二进制的运算,参见“位运算”部分的讲解。

print(bin(4)) # 0b100
print(bin(5)) # 0b101
print(bin(~4), ~4) # -0b101 -5
print(bin(4 & 5), 4 & 5) # 0b100 4
print(bin(4 | 5), 4 | 5) # 0b101 5
print(bin(4 ^ 5), 4 ^ 5) # 0b1 1
print(bin(4 << 2), 4 << 2) # 0b10000 16
print(bin(4 >> 2), 4 >> 2) # 0b1 1
0b100
0b101
-0b101 -5
0b100 4
0b101 5
0b1 1
0b10000 16
0b1 1
三元运算符

【例子】

x, y = 4, 5
if x < y:
small = x
else:
small = y

print(small) # 4
4
有了这个三元操作符的条件表达式,你可以使用一条语句来完成以上的条件判断和赋值操作。

【例子】

x, y = 4, 5
small = x if x < y else y
print(small) # 4
4
其他运算符

操作符 名称 示例
in 存在 ‘A’ in [‘A’, ‘B’, ‘C’]
not in 不存在 ‘h’ not in [‘A’, ‘B’, ‘C’]
is 是 “hello” is “hello”
not is 不是 “hello” is not “hello”
【例子】

letters = [‘A’, ‘B’, ‘C’]
if ‘A’ in letters:
print(‘A’ + ’ exists’)
if ‘h’ not in letters:
print(‘h’ + ’ not exists’)

A exists

h not exists

A exists
h not exists
【例子】比较的两个变量均指向不可变类型。

a = “hello”
b = “hello”
print(a is b, a == b) # True True
print(a is not b, a != b) # False False
True True
False False
【例子】比较的两个变量均指向可变类型。

a = [“hello”]
b = [“hello”]
print(a is b, a == b) # False True
print(a is not b, a != b) # True False
False True
True False
注意:

is, is not 对比的是两个变量的内存地址
==, != 对比的是两个变量的值
比较的两个变量,指向的都是地址不可变的类型(str等),那么is,is not 和 ==,!= 是完全等价的。
对比的两个变量,指向的是地址可变的类型(list,dict,tuple等),则两者是有区别的。
运算符的优先级

一元运算符优于二元运算符。例如3 ** -2等价于3 ** (-2)。
先算术运算,后移位运算,最后位运算。例如 1 << 3 + 2 & 7等价于 1 << (3 + 2)) & 7。
逻辑运算最后结合。例如3 < 4 and 4 < 5等价于(3 < 4) and (4 < 5)。
【例子】

print(-3 ** 2) # -9
print(3 ** -2) # 0.1111111111111111
print(1 << 3 + 2 & 7) # 0
print(-3 * 2 + 5 / -2 - 4) # -12.5
print(3 < 4 and 4 < 5) # True
-9
0.1111111111111111
0
-12.5
True
3. 变量和赋值
在使用变量之前,需要对其先赋值。
变量名可以包括字母、数字、下划线、但变量名不能以数字开头。
Python 变量名是大小写敏感的,foo != Foo。
【例子】

teacher = “老马的程序人生”
print(teacher) # 老马的程序人生
老马的程序人生
【例子】

first = 2
second = 3
third = first + second
print(third) # 5
5
【例子】

myTeacher = “老马的程序人生”
yourTeacher = “小马的程序人生”
ourTeacher = myTeacher + ‘,’ + yourTeacher
print(ourTeacher) # 老马的程序人生,小马的程序人生
老马的程序人生,小马的程序人生
4. 数据类型与转换
类型 名称 示例
int 整型 <class ‘int’> -876, 10
float 浮点型<class ‘float’> 3.149, 11.11
bool 布尔型<class ‘bool’> True, False
整型

【例子】通过 print() 可看出 a 的值,以及类 (class) 是int。

a = 1031
print(a, type(a))

1031 <class ‘int’>

1031 <class ‘int’>

Python 里面万物皆对象(object),整型也不例外,只要是对象,就有相应的属性 (attributes) 和方法(methods)。

【例子】

b = dir(int)
print(b)

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’,

delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’,

float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’,

getattribute’, ‘getnewargs’, ‘gt’, ‘hash’,

index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’,

le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’,

neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’,

rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’,

rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’,

round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’,

rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’,

sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’,

‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’,

‘numerator’, ‘real’, ‘to_bytes’]

[‘abs’, ‘add’, ‘and’, ‘bool’, ‘ceil’, ‘class’, ‘delattr’, ‘dir’, ‘divmod’, ‘doc’, ‘eq’, ‘float’, ‘floor’, ‘floordiv’, ‘format’, ‘ge’, ‘getattribute’, ‘getnewargs’, ‘gt’, ‘hash’, ‘index’, ‘init’, ‘init_subclass’, ‘int’, ‘invert’, ‘le’, ‘lshift’, ‘lt’, ‘mod’, ‘mul’, ‘ne’, ‘neg’, ‘new’, ‘or’, ‘pos’, ‘pow’, ‘radd’, ‘rand’, ‘rdivmod’, ‘reduce’, ‘reduce_ex’, ‘repr’, ‘rfloordiv’, ‘rlshift’, ‘rmod’, ‘rmul’, ‘ror’, ‘round’, ‘rpow’, ‘rrshift’, ‘rshift’, ‘rsub’, ‘rtruediv’, ‘rxor’, ‘setattr’, ‘sizeof’, ‘str’, ‘sub’, ‘subclasshook’, ‘truediv’, ‘trunc’, ‘xor’, ‘bit_length’, ‘conjugate’, ‘denominator’, ‘from_bytes’, ‘imag’, ‘numerator’, ‘real’, ‘to_bytes’]
对它们有个大概印象就可以了,具体怎么用,需要哪些参数 (argument),还需要查文档。看个bit_length()的例子。

【例子】找到一个整数的二进制表示,再返回其长度。

a = 1031
print(bin(a)) # 0b10000000111
print(a.bit_length()) # 11
0b10000000111
11
浮点型

【例子】

print(1, type(1))

1 <class ‘int’>


print(1., type(1.))

1.0 <class ‘float’>


a = 0.00000023
b = 2.3e-7
print(a) # 2.3e-07
print(b) # 2.3e-07
1 <class ‘int’>
1.0 <class ‘float’>
2.3e-07
2.3e-07
有时候我们想保留浮点型的小数点后 n 位。可以用 decimal 包里的 Decimal 对象和 getcontext() 方法来实现。

import decimal
from decimal import Decimal
Python 里面有很多用途广泛的包 (package),用什么你就引进 (import) 什么。包也是对象,也可以用上面提到的dir(decimal) 来看其属性和方法。

【例子】getcontext() 显示了 Decimal 对象的默认精度值是 28 位 (prec=28)。

a = decimal.getcontext()
print(a)

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,

capitals=1, clamp=0, flags=[],

traps=[InvalidOperation, DivisionByZero, Overflow])

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])
b = Decimal(1) / Decimal(3)
print(b)

0.3333333333333333333333333333

0.3333333333333333333333333333
【例子】使 1/3 保留 4 位,用 getcontext().prec 来调整精度。

decimal.getcontext().prec = 4
c = Decimal(1) / Decimal(3)
print©

0.3333

0.3333
布尔型

布尔 (boolean) 型变量只能取两个值,True 和 False。当把布尔型变量用在数字运算中,用 1 和 0 代表 True 和 False。

【例子】

print(True + True) # 2
print(True + False) # 1
print(True * False) # 0
2
1
0
除了直接给变量赋值 True 和 False,还可以用 bool(X) 来创建变量,其中 X 可以是

基本类型:整型、浮点型、布尔型
容器类型:字符串、元组、列表、字典和集合
【例子】bool 作用在基本类型变量:X 只要不是整型 0、浮点型 0.0,bool(X) 就是 True,其余就是 False。

print(type(0), bool(0), bool(1))

<class ‘int’> False True


print(type(10.31), bool(0.00), bool(10.31))

<class ‘float’> False True


print(type(True), bool(False), bool(True))

<class ‘bool’> False True

<class ‘int’> False True
<class ‘float’> False True
<class ‘bool’> False True
【例子】bool 作用在容器类型变量:X 只要不是空的变量,bool(X) 就是 True,其余就是 False。

print(type(’’), bool(’’), bool(‘python’))

<class ‘str’> False True


print(type(()), bool(()), bool((10,)))

<class ‘tuple’> False True


print(type([]), bool([]), bool([1, 2]))

<class ‘list’> False True


print(type({}), bool({}), bool({‘a’: 1, ‘b’: 2}))

<class ‘dict’> False True


print(type(set()), bool(set()), bool({1, 2}))

<class ‘set’> False True

<class ‘str’> False True
<class ‘tuple’> False True
<class ‘list’> False True
<class ‘dict’> False True
<class ‘set’> False True
确定bool(X) 的值是 True 还是 False,就看 X 是不是空,空的话就是 False,不空的话就是 True。

对于数值变量,0, 0.0 都可认为是空的。
对于容器变量,里面没元素就是空的。
获取类型信息

获取类型信息 type(object)
【例子】

print(isinstance(1, int)) # True
print(isinstance(5.2, float)) # True
print(isinstance(True, bool)) # True
print(isinstance(‘5.2’, str)) # True
True
True
True
True
注:

type() 不会认为子类是一种父类类型,不考虑继承关系。
isinstance() 会认为子类是一种父类类型,考虑继承关系。
如果要判断两个类型是否相同推荐使用 isinstance()。

类型转换

转换为整型 int(x, base=10)
转换为字符串 str(object=’’)
转换为浮点型 float(x)
【例子】

print(int(‘520’)) # 520
print(int(520.52)) # 520
print(float(‘520.52’)) # 520.52
print(float(520)) # 520.0
print(str(10 + 10)) # 20
print(str(10.1 + 5.2)) # 15.3
520
520
520.52
520.0
20
15.3
5. print() 函数
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
将对象以字符串表示的方式格式化输出到流文件对象file里。其中所有非关键字参数都按str()方式进行转换为字符串输出;
关键字参数sep是实现分隔符,比如多个参数输出时想要输出中间的分隔字符;
关键字参数end是输出结束时的字符,默认是换行符\n;
关键字参数file是定义流输出的文件,可以是标准的系统输出sys.stdout,也可以重定义为别的文件;
关键字参数flush是立即把内容输出到流文件,不作缓存。
【例子】没有参数时,每次输出后都会换行。

shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(“This is printed without 'end’and ‘sep’.”)
for item in shoplist:
print(item)

This is printed without 'end’and ‘sep’.

apple

mango

carrot

banana

This is printed without 'end’and ‘sep’.
apple
mango
carrot
banana
【例子】每次输出结束都用end设置的参数&结尾,并没有默认换行。

shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(“This is printed with ‘end=’&’’.”)
for item in shoplist:
print(item, end=’&’)
print(‘hello world’)

This is printed with ‘end=’&’’.

apple&mango&carrot&banana&hello world

This is printed with ‘end=’&’’.
apple&mango&carrot&banana&hello world
【例子】item值与’another string’两个值之间用sep设置的参数&分割。由于end参数没有设置,因此默认是输出解释后换行,即end参数的默认值为\n。

shoplist = [‘apple’, ‘mango’, ‘carrot’, ‘banana’]
print(“This is printed with ‘sep=’&’’.”)
for item in shoplist:
print(item, ‘another string’, sep=’&’)

This is printed with ‘sep=’&’’.

apple&another string

mango&another string

carrot&another string

banana&another string

This is printed with ‘sep=’&’’.
apple&another string
mango&another string
carrot&another string
banana&another string
位运算

  1. 原码、反码和补码
    二进制有三种不同的表示形式:原码、反码和补码,计算机内部使用补码来表示。

原码:就是其二进制表示(注意,有一位符号位)。

00 00 00 11 -> 3
10 00 00 11 -> -3
反码:正数的反码就是原码,负数的反码是符号位不变,其余位取反(对应正数按位取反)。

00 00 00 11 -> 3
11 11 11 00 -> -3
补码:正数的补码就是原码,负数的补码是反码+1。

00 00 00 11 -> 3
11 11 11 01 -> -3
符号位:最高位为符号位,0表示正数,1表示负数。在位运算中符号位也参与运算。

  1. 按位运算
    按位非操作 ~
    ~ 1 = 0
    ~ 0 = 1
    ~ 把num的补码中的 0 和 1 全部取反(0 变为 1,1 变为 0)有符号整数的符号位在 ~ 运算中同样会取反。

00 00 01 01 -> 5
~

11 11 10 10 -> -6

11 11 10 11 -> -5
~

00 00 01 00 -> 4
按位与操作 &
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
只有两个对应位都为 1 时才为 1

00 00 01 01 -> 5
&
00 00 01 10 -> 6

00 00 01 00 -> 4
按位或操作 |
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
只要两个对应位中有一个 1 时就为 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6

00 00 01 11 -> 7
按位异或操作 ^
1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0
只有两个对应位不同时才为 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6

00 00 00 11 -> 3
异或操作的性质:满足交换律和结合律

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

ABA: = AAB = B = 00 00 01 11
按位左移操作 <<
num << i 将num的二进制表示向左移动i位所得的值。

00 00 10 11 -> 11
11 << 3

01 01 10 00 -> 88
按位右移操作 >>
num >> i 将num的二进制表示向右移动i位所得的值。

00 00 10 11 -> 11
11 >> 2

00 00 00 10 -> 2
3. 利用位运算实现快速计算
通过 <<,>> 快速计算2的倍数问题。

n << 1 -> 计算 n2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n
(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n
通过 ^ 快速交换两个整数。 通过 ^ 快速交换两个整数。

a ^= b
b ^= a
a ^= b
通过 a & (-a) 快速获取a的最后为 1 位置的整数。

00 00 01 01 -> 5
&
11 11 10 11 -> -5

00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14

00 00 00 10 -> 2
4. 利用位运算实现整数集合
一个数的二进制表示可以看作是一个集合(0 表示不在集合中,1 表示在集合中)。

比如集合 {1, 3, 4, 8},可以表示成 01 00 01 10 10 而对应的位运算也就可以看作是对集合进行的操作。

元素与集合的操作:

a | (1<<i) -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i) -> 判断 i 是否属于该集合(零不属于,非零属于)
集合之间的操作:

a 补 -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)
注意:整数在内存中是以补码的形式存在的,输出自然也是按照补码输出。

【例子】C#语言输出负数。

class Program
{
static void Main(string[] args)
{
string s1 = Convert.ToString(-3, 2);
Console.WriteLine(s1);
// 11111111111111111111111111111101

    string s2 = Convert.ToString(-3, 16);
    Console.WriteLine(s2); 
    // fffffffd
}

}
【例子】 Python 的bin() 输出。

print(bin(3)) # 0b11
print(bin(-3)) # -0b11

print(bin(-3 & 0xffffffff))

0b11111111111111111111111111111101


print(bin(0xfffffffd))

0b11111111111111111111111111111101


print(0xfffffffd) # 4294967293
0b11
-0b11
0b11111111111111111111111111111101
0b11111111111111111111111111111101
4294967293
是不是很颠覆认知,我们从结果可以看出:

Python中bin一个负数(十进制表示),输出的是它的原码的二进制表示加上个负号,巨坑。
Python中的整型是补码形式存储的。
Python中整型是不限制长度的不会超范围溢出。
所以为了获得负数(十进制表示)的补码,需要手动将其和十六进制数0xffffffff进行按位与操作,再交给bin()进行输出,得到的才是负数的补码表示。


  1. mermaid语法说明 ↩︎

  2. 注脚的解释 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值