莫愁 Python基础

2019-07-26  本文已影响0人  Smnag
改变tab

选中——command+[

for循环
for i in range(1,10,2)
#range范围:前闭后开
#步长为2
    print(i)
升级模块

sudo pip3 install -U NumPy

写入文件
text = 'This is my first line.\nThis is another line.'
#/n换行符
my_file = open('my file.txt','w')
#如文件存在,open会打开它;否则,新建
#'w'为写入模式,'r'为只读,'a'为追加
my_file.write(text)
my_file.close()
#文件读取/写入后要关闭
读取文件
file = open('my file.txt','r')
content = file.readlines()
#readline为只读一行
print(content)
列表和元组
list.append()
list.insert(1,0)
#列表位置1,添加0
list.remove(写value,而非序号)
print(list[-1])
#打印列表最后一位 
print(list[:3])
#打印第0到第3位
print(list[5:])
#打印第5位之后的数
print(list[-3:])
#打印倒数后三位
print(list.index(value)) 
#打印索引
print(list.count(value))
#统计某个value出现了几次
list.sort()
#从大到小排序
list.sort(reverse=True)
#从小到大排序
多维列表

多维列表索引
print(multi_dim_list[0][0])

字典

字典没有顺序,列表有顺序
d = { key1:value1, key2:value2, key3:value3, ....}

删除字典中的键值对

del d[key]

增加字典中的键值对

d[key4] = value4
import官方模块
import time as t
#引用时写 t.
from time import time,locatime
#引用时可不用写time.
form time import *
#引用时可不用写time
import自己的模块

1.保存自己写的模块
2.将模块放入python的site-package文件夹中或要调用的文件的同一文件夹中

continue和break
错误处理try
try:
    file = open('e','r+')
except Exception as e:
    print('There is no file named as e.')
    response = input('Do you want to create a new file? ')
    if response == 'Y'
        file = open('e','w')
    else:
        pass
else:
    file.write('s')
file.close()
屏幕快照 2019-08-01 下午2.07.48.png
上一篇 下一篇

猜你喜欢

热点阅读