常用的数字数据类型
Name | Notation | e.g. |
---|---|---|
Integers | int | a = 10 |
Floating | float | b = 3.14 |
Complex | complex | c = 1 + 2j |
String | str | d = ‘Python’ |
浮点数的精度
- 尝试在您的控制台中键入0.1 + 0.2。 你会发现这个值是
- 0.30000000000000004 这是二进制浮点的本质。 您可以在支持硬件浮点运算的所有语言中看到同样的东西。 可以使用“round()”功能控制显示精度,但也有上述情况,这意味着round(9.995,2)返回9.99而不是10,因为9.995的存储稍小于9.995。
- decimal Library将给出精确的存储值,请参见以下示例。
import decimal
# import the libray "decimal"
# display 2 decimal precision
print (round (3*1415 , 2)) # result 3. 14
print (round (9 .995 , 2)) # result 9. 99
#call function "Decimal " from lib "decimal"
print (decimal.Decimal (9.995))
The last "print" returns
9.9949999999999992184029906638897955417633056640625,
which is exactly how 9.995 is stored in the hardware.
字符串str的一些功能
t = 'He is a string. Who are you?'
print(t.capitalize()) # Cap first letter
print(t.split()) # split by words
print(t.find('i')) # return index of 'i'
print(t.find('in')) # index of 'i' in 'in'
print(t.find('Python')) # find sth not in
print(t[0:4]) # returu from index 0 to 3
print(t.replace(' ','|')) # replace by '|'
w = 'http://www.google.com'
print(w.strip('http://')) #delete sth
He is a string. who are you?
['He', 'is', 'a', 'string.', 'Who', 'are', 'you?']
11
-1
He i
He|is|a|string.|Who|are|you?
www.google.com
Python功能:索引
可以通过[ ]来引用数据中的值
基本的数据结构
注意列表是方括号
列表的一些有用功能
l = [1, 2, 3.14, 'data'] #list
l.append ([4, 3]) #添加一个元素
print (l)
l.extend (['delta' ,5 ,6] ) #添加一个新列表
print(l)
l.insert(3, 'beta') #在第3之前插入。
print(l)
l.remove ('data') #删除一个元素
print(l)
参考对象
当一个变量指向另一个变量时,两变量变动将同步
x = [1, 2,3, 4]
y = x
y[0] = 5
print(x)
x = [1, 2, 3, 4]
z = x.copy()
z[0] = 5
print (x)
#输出
[5, 2, 3, 4]
[1, 2, 3, 4]
多维列表
列表中可以包含列表
a = [[1,2 , 3 ,4],[1,2 ,3,4],[1,2 ,3]]
print(a)
print(a[0][3])
#输出
[[1, 2, 3, 4], [1, 2, 3, 4], [1, 2, 3]]
4
读取/写入文件
1. 内建open()方法
打开文件
open()方法返回一个文件对象,最常用的一般使用两个参数。
file_object = open(filename, mode)
这个mode参数可以是:
‘r’ 只读模式(when the file will only be read)
‘w’ 只写模式(与一个现存文件文件同名,则被清除)
‘a’ 添加模式,即任意写入文件的数据都被自动添加到末尾
‘r+’ 打开文件,可以读、写
2. 创建一个文件 w
file = open('newfile.txt', 'w')
file.write('I am created for the course. \n')
file.write('How about you? ')
file.write('How is your exam?')
file.close()
3. 读取一个文件
查看文件
file = open('newfile.txt', 'r')
#show whole efile
print(file.read())
#show first ten characterrs
print(file.read(10))
#view by line
print(file.readline())
#view all by line
print(file.readlines())
file.close()
4. 循环读取一个文件 r
file = open('newfile.txt', 'r')
for line in file:
print (line)
file.close()
#输出
I am created for the course.
How about you? How is your exam?
5. 增加一个文件 a
写入文件的数据都被自动添加到末尾
file = open('newfile.txt', 'a')
file.write('\nI am back again. \n')
file.write('Do you miss me?\n')
file.clase()
#输出
I am created for the course.
How about you? How is your exam?
I am back again.
Do you miss me?
文件路径
可以使用绝对路径指定文件名
open('C:\Users\user\Documents\file.txt')
请注意,反斜杠需要转义(写入两次’’)