代码及写代码

  • 什么是代码:

代码是现实世界事物在计算机世界中的映射。

  • 什么是写代码:

写代码是将现实世界中的事物用计算机语言来描述

画画、摄影:光影、图形、颜色、结构

我的世界:石英、矿石、水晶

计算机语言:基本数据类型


Number(数字类型)

整数:int

浮点数:float

其他语言:对于浮点数,还分为单精度(float),双精度(double)

其他语言:对于整数,还分为short,int,long

bool布尔类型:True 真;False 假

复数:complex

  • 整数与浮点数:
>>> type(1)<class 'int'>>>> type(1.1)<class 'float'>>>> type(-21)<class 'int'>>>> type(-1.1111)<class 'float'>

>>> type(1+1)<class 'int'>>>> type(1+1.0)<class 'float'>>>> type(7.2-4)<class 'float'>>>> type(1*1.11)<class 'float'>>>> type(4.0/2)<class 'float'>>>> type(2/2)               #python中除法结果为浮点数<class 'float'>>>> type(2//2)              # //表示地板除,类似整除,删除小数点后的商数<class 'int'>

  • 进制:

10进制,2进制,8进制,16进制。

2进制:0b,例如0b10表示10进制的2

>>> 0b102

8进制:0o,例如0o11表示10进制的9

>>> 0o119

16进制:0x,例如0x18表示10进制的24

>>> 0x1824

而对于10进制,python没有额外的表示方式,默认就是10进制。

  • 进制的转换:

bin()可将其他进制的数转换为2进制

>>> bin(10)'0b1010'>>> bin(0o7)'0b111'>>> bin(0xE)'0b1110'

oct()可将其他进制的数转换为8进制

>>> oct(10)'0o12'>>> oct(0b11111)'0o37'>>> oct(0x1F)'0o37'

int()可将其他进制的数转换为10进制

>>> int(0b1111)15>>> int(0o77)63>>> int(0x1A)26

hex()可将其他进制的数转换为16进制

>>> hex(888)'0x378'>>> hex(0b11111)'0x1f'>>> hex(0o777)'0x1ff'

  • bool布尔类型:
>>> type(True)<class 'bool'>>>> type(False)<class 'bool'>>>> int(True)1>>> int(False)0>>> bool(1)True>>> bool(-1.1)True>>> bool(0)False>>> bool(None)False

非零数字都可以表示True,数字0表示False;除了数字之外,非空的字符串、列表、集合等等类型都可以表示True,而这些为空时表示False。


Str(字符串类型)

在Python中如何表示字符串?使用单引号、双引号和三引号来表示字符串,不管哪种引号都一定要成对出现,否则出错。

使用三引号定义的字符串是文档字符串,通常用作注释说明。

>>> '''
hello world
hello world
hello world
''''\nhello world\nhello world\nhello world\n'

\n表示换行符,\t表示Tab键

  • 转义字符:

转义字符通常用于转义特殊的字符。特殊的字符包括:

  1. 无法“看见”的字符
  2. 与语言本身语法有冲突的字符

常用转义字符包括:

\n      换行符

\'      单引号

\"      双引号

\\      反斜杠符号\

\t      横向制表符(Tab键)

\r      回车,与\n不同

  • 原始字符串:

当一个字符串前加上r/R后,这个字符串就是一个原始字符串,不需要转义。

>>> print('c:\north\northwest')c:orth
orthwest>>> print('c:\\north\\northwest')c:\north\northwest>>> print(r'c:\north\northwest')c:\north\northwest

  • 字符串运算:

加法:

>>> 'hello' + 'world''helloworld'

乘法:

>>> 'hello' * 3'hellohellohello'>>> 'hello'  *  'world'Traceback (most recent call last):
  File "", line 1, in <module>
    'hello'  *  'world'TypeError: can't multiply sequence by non-int of type 'str'

可见字符串只能与数字相乘,字符串不能与字符串相乘。

截取:

>>> 'hello world'[0]'h'>>> 'hello world'[1]'e'>>> 'hello world'[2]'l'

>>> 'hello world'[-1]'d'>>> 'hello world'[-2]'l'>>> 'hello world'[-3]'r'

可见字符串的截取,正向截取时下标从0开始,而下标为1的表示字符串的第二个字符;反向截取时下标从-1开始,即从倒数第一个字符开始截取。

切片:

>>> 'hello world'[0:4]'hell'>>> 'hello world'[0:5]'hello'>>> 'hello world'[7:12]'orld'>>> 'hello world'[6:11]'world'>>> 'hello world'[6:20]'world'

>>> 'hello world'[0:-1]'hello worl'>>> 'hello world'[-5:-1]'worl'>>> 'hello world'[-5:]'world'

可见,字符串的切片遵循“左包右不包”的原则,即右下标的字符不会被截取在内。其实也可以将右下标理解为“步长”,在“步长”内的字符不会被截取。