疯狂Python讲义-李刚编著-第2章变量和简单类型

第2章 变量和简单类型

2.1.单行注释和多行注释

2.2.变量

2.2.1.Python 是弱类型语言

a = 5
type(a)

2.2.2.使用 print 函数输出变量

#格式
#flush 参数用于控制输出缓存,该参数一般保持为 False 即可,这样可以获得较好的性能
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

#同时输出多个变量和字符串
user_name = 'Charlie'
user_age = 8
print("读者名:",  user_name, "年龄:", user_age)

#同时输出多个变量和字符串,指定分隔符
print("读者名:",  user_name, "年龄:", user_age, sep='|')

#设置 end 参数,指定输出之后不再换行
print(40, '\t', end="")
print(50, '\t', end="")
print(60, '\t', end="")

#改变参数让 print 函数输出到特定文件中
f = open("poem.txt", "w")
print('沧海月明珠有泪', file = f)
print('蓝田日暖玉生烟', file = f)
f.close()

2.2.3.变量的命名规则

2.2.4. Python 的关键字和内置函数

Python 关键字
False None True and as
assert 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    

 

#导入 keyword 模块
import keyword

#显示所有关键字
keyword.kwlist

  

Python 内置函数
abs() all() any() basestring() bin()
bool() bytearray() callable() chr() classmethod()
cmp() compile() complex() delattr()  dict() 
dir() divmod()  enumerate()  eval()  execfile() 
file()  filter()  float()  format()  frozenset() 
getattr() globals()  hasattr() hash() help()
hex() id() input() int() isinstance()
issubclass() iter() len()  list() locals()
long() map() max() memoryview() min()
next() object() oct() open() ord()
pow() print() property() range() raw_input()
reduce() reload() repr() reversed() zip()
round() set() setattr() slice() sorted()
staticmethod() str() sum() super() tuple()
type() unichr() unicode() vars() xrange()
Zip() __import__() apply()  buffer()  coerce() 
intern        

2.3.数值类型

2.3.1.整型

Python 的整型支持 None 值(空值)

Python 的整型数值有4种表达形式

1.十进制形式:最普通的整数

2.二进制形式:以 0b 或 0B 开头的整数

3.八进制形式:以 0o 或 0O 开头的整数

4.十六进制形式:以 0x 或 0X 开头的整数

为了提高数值(包括浮点型)的可读性,Python 3.x 允许为数值(包括浮点型)增加下划线作为分隔符。这些下划线并不会影响数值本身。

one_million = 1_000_000
print(one_million)
price = 234_234_234 

2.3.2.浮点型

Python 的 浮点数有两种表示形式

1.十进制形式

2.科学计数形式:例如 5.12e2(即 5.12 x 102

2.3.3.复数

复数的虚部用 j 或 J 来表示

如果需要在程序中对复数进行计算,可导入 Python 的 cmath 模块(c 代表 complex),在该模块下包含了各种支持复数运算的函数

ac1 = 3 + 0.2j
print(ac1)
print(type(ac1))
ac2 = 4 - 0.1j
print(ac2)
print(ac1 + ac2)
import cmath
ac3 = cmath.sqrt(-1)
print(ac3)

2.4.字符串入门

2.4.1.字符串和转义字符

提示:Python 3.x 对中文字符支持较好,但 Python 2.x 则要求在源程序中增加 "#coding:utf8" 才能支持中文字符

Python 允许使用反斜线(\)将字符串中的特殊字符进行转义。

2.4.2.拼接字符串

s1 = "hello," 'Charlie'
print(s1)

s2 = "Python "
s3 = "is Funny"
s4 = s2 + s3
print(s4)

2.4.3.repr 和字符串

Python 不允许直接拼接数值和字符串

为了将数值转换成字符串,可以使用 str() 和 repr() 函数

s1 = "这本书的价格是:"
p = 99.8

#报错
print(s1+p)

#使用 str() 将数值转换成字符串
print(s1+str(p))

#使用 repr() 将数值转换成字符串
print(s1+repr(p))

str 本身是 Python 内置的类型,而 repr() 则只是一个函数。此外,repr 还有一个功能,它会以 Python 表达式的形式来表示值。

st = "I will play my fife"
print(st)
print(repr(st))

上面代码中 st 本身就是一个字符串,但程序依然使用了 repr() 对字符串进行转换。可看到的运行结果如下:

I will play my fife
'I will play my fife'

提示:在交互式解释器中输入一个变量或表达式时,Python 会自动使用 repr() 函数处理该变量或表达式

2.4.4.使用 input 和 raw_input 获取用户输入  

2.4.5.长字符串

2.4.6.原始字符串

比如写一条 Windows 的路径:G:\publish\codes\02\2.4,如果在 Python 程序中直接这样写肯定是不行的,需要写成:G:\\publish\\codes\\02\\2.4,这很烦人,此时可借助于原始字符串来解决这个问题。

原始字符串以 "r" 开头,原始字符串不会把反斜线当成特殊字符

s1 = r'G:\publish\codes\02\2.4'
print(s1)

2.4.7.字节串(bytes)

Python 3 新增了 bytes 类型,用于代表字节串(这是作者生造的一个词,与字符串对应)。

由于 bytes 保存的就是原始的字节(二进制格式)数据,因此 bytes 对象可用于在网络上传输数据,也可用于存储各种二进制格式的文件,比如图片、音乐等文件。

如果希望将一个字符串转换成 bytes 对象,有如下三种方式:

1.如果字符串内容都是 ASCII 字符,则可以通过直接在字符串之前添加 b 来构建字符串值

2.调用 bytes() 函数(其实是 bytes 的构造方法)将字符串按指定字符集转换成字符串,如果不指定字符集,默认使用 UTF-8 字符集

3.调用字符串本身的 encode() 方法将字符串按指定字符集转换成字符串,如果不指定字符集,默认使用 UTF-8 字符集

#创建一个空的 bytes
b1 = bytes()

#创建一个空的 bytes 值
b2 = b''

#通过 b 前缀指定 hello 是 bytes 类型的值
b3 = b'hello'

print(b3)
print(b3[0])
print(b3[2:4])

#调用 bytes 方法将字符串转换成 bytes 对象
b4 = bytes('我爱 Python 编程', encoding='utf-8')
print(b4)

#利用字符串的 encode() 方法编码成 bytes,默认使用 UTF-8 字符集
b5 = "学习 Python 很有趣".encode('utf-8')
print(b5)

提示:计算机底层有两个基本概念:位(bit)和字节(Byte),其中 bit 代表 1 位,Byte 代表一个字节,1 个字节包含 8 位。 

如果程序获得了 bytes 对象,也可调用 bytes 对象的 decode() 方法将其解码成字符串

2.5.深入使用字符串

2.5.1.转义字符

2.5.2.字符串格式化

Python 提供了 "%" 对各种类型的数据进行格式化输出

price = 108
print("this book's price is %s" % price)

user = "Charlie"
age = 8
print("%s is a %s years old boy" % (user, age))

my_value = 3.001415926535
#最大宽度为8,小数点后保留3位
print("my_value is: %8.3f" % my_value)
print("my_value is: %08.3f" % my_value)
print("my_value is: %+08.3f" % my_value)

#只保留3个字符
print("the name is: %.3s" % user)
print("the name is: %10.2s" % user)

2.5.3.序列相关

s = 'crazyit.org is very good'
print(s[2])
print(s[-4])
print(s[3:5])
print(s[3:-5])
print(s[-6:-3])
print(s[5:])
print(s[-6:]) #输出 y good
print(s[:5])
print(s[:-6])
print('very' in s)
print('fkit' in s)
print(len(s))
print(len('test'))
print(max(s)) #z
print(min(s)) #空格

2.5.4.大小写相关方法

str 类提供的所有的方法,其中以 "__" 开头、"__" 结尾的方法被约定成私有方法,不希望被外部直接调用

dir():列出指定类或模块包含的全部内容(包括函数、方法、类、变量等)

help():查看某个函数或方法的帮助文档

title():将每个单词的首字母改为大写

lower():将整个字符串改为小写

upper():将整个字符串改为大写

2.5.5.删除空白

Python 的 str 是不可变的(字符串一旦形成,它所包含的字符序列就不能发生任何改变)

strip():删除字符串前后的空白

lstrip():删除字符串前面(左边)的空白

rstrip():删除字符串后面(右边)的空白

#示范删除字符串前后指定字符的功能
s2 = 'i think it is a scarecrow'

#删除左边的i、t、o、w 字符
print(s2.lstrip('itow'))

#删除右边的i、t、o、w 字符
print(s2.rstrip('itow'))

#删除两边的i、t、o、w 字符
print(s2.strip('itow'))

2.5.6.查找、替换相关方法

startswitch():判断字符串是否以指定子串开头

endswitch():判断字符串是否以指定子串结尾

find():查找指定子串在字符串中出现的位置,如果没有找到指定子串,则返回 -1

index():查找指定子串在字符串中出现的位置,如果没有找到指定子串,则引发 ValueError 错误

replace():使用指定子串替换字符串中的目标子串

translate():使用指定的翻译映射表对字符串执行替换

maketrans():通过该方法可以非常方便地创建翻译映射表

table = {97:945, 98:946, 116:964}
print(s.translate(table))

table = str.maketrans('abc', '123')
print(table)

#输出内容
{97:49, 98:50, 99:51}

2.5.7.分割、连接方法

split():将字符串按指定分隔符分割成多个短语

join():将多个短语连接成字符串

2.6.运算符

2.6.1.赋值运算符

2.6.2.算术运算符

**:乘方运算符

2.6.3.位运算符

2.6.4.扩展后的赋值运算符

2.6.5.索引运算符

2.6.6.比较运算符和 bool 类型

is:判断两个变量所引用的对象是否相同,如果相同则返回 True

is not:判断两个变量所引用的对象是否不相同,如果不相同则返回 True

Python 提供了一个全局的 id() 函数来判断变量所引用的对象的内存地址(相当于对象在计算机内存中存储位置的门牌号),如果两个对象所在的内存地址相同,则说明这两个对象其实是同一个对象。由此可见,is 判断其实就是要求通过 id() 函数计算两个对象时返回相同的地址。

2.6.7.逻辑运算符

2.6.8.三目运算符

语法格式:True_statements if expression else False_statements

a = 5
b = 3
st = "a 大于 b" if a > b else "a 不大于 b"
print(st)

c = 5
d = 5
print("c 大于 d") if c > d else (print("c 小于 d") if c < d else print("c 等于 d"))

2.6.9.in 运算符

2.6.10.运算符的结合性和优先级

运算符说明 Python 运算符 优先级
索引运算符 x[index] 或 x[index:index2[:index3]] 18、19
属性访问 x.attribute 17
乘方      ** 16
按位取反 ~ 15
符号运算符 +或- 14
乘、除 *、/、//、% 13
加、减 +、- 12
位移 >>、<< 11
按位与 & 10
按位异或 ^ 9
按位或 | 8
比较运算符 ==、!=、>、>=、<、<= 7
is 运算符 is、is not 6
in 运算符 in、not in 5
逻辑非 not 4
逻辑与 and 3
逻辑或 or 2

posted on 2020-01-13 09:27  herisson_pan  阅读(13)  评论(0)    收藏  举报

导航