1.python中的循环
for循环
格式:
for 临时变量 in 可迭代对象:
循环体:
name = 'neusoft'
for x in name:
print(x)
if x == 's':
print('python的学习')
这个X是什么 x是临时变量不用提前声明 python自动为你创建
循环次数在哪里?
range(起始位置,终止位置,步长)可以写循环次数
起始位置省略,默认为0,步长省略为1,范围为左闭右开
for i in range(1,101,2):
print('这是说喜欢你的第',i,'次')
循环不停的append
heroList=['鲁班七号',"安琪拉","李白","后裔",100,1.0]
print(heroList)
遍历heroList
for hero in heroList:
print(hero)
len() 可以检测对象的元素个数
for i in range(len(heroList)):
print(heroList[i])
if heroList[i] == '后裔':
print('恭喜你选择隐藏英雄')
else:
print('没有选择隐藏英雄')
2.添加元素 append 是在列表的末尾添加元素
heroList.append('鲁班大师')
print('添加后的列表',heroList)
3.修改
heroList[4] ="貂蝉"
print("修改后的列表",heroList)
4.删除
del heroList[5]
print("删除后的列表",heroList)
字符串
表示 '' " "
要注意的是
name = "k"o"be"
name = 'k"o"be'
访问
print(name[2])
修改
name[1] = "x"
print(name)
name = "kobe"
print(name)
常用操作
字符串的替换
price = '¥9.9'
price = price.replace("¥", '')
print(price)
价格涨价 10倍
new_price = float(price) *10
print(new_price)
strip 去空格操作
name = ' neuedu '
print(len(name))
name = name.strip()
print(len(name))
join 将列表变成字符串
li = ['你', '好', '帅']
disk_path = ['C:','Users', 'Administrator', 'Desktop', 'CCF']
path = '\\'.join(disk_path)
print(path)
li = ''.join(li)
print(li)
元组
tuple()
list()
int()
str()
创建
元组和列表很相似,只不过不能修改
a = (1, '1', 3)
print(a)
print(type(a))
访问
print(a[2])
a[2] = 6
元组的用处:
1, 写保护 ,安全, Python内置函数返回的类型都是元组
2, 相对列表来讲, 元组更节省空间, 效率更高
我们经常使用的组合方式:
list2 = [('a',22),('b', 33),('c',99)]
4字典
创建字典 key -value
info = {'name': '崔天驰', 'age': 18, 'gender':'female'}
print(type(info))
访问字典 通过建访问值
print(info['name'])
访问不存在的键
print(info['addr'])
当不存在这键的时候,可以返回默认设置的值,
有这个键就正常返回
修改
info['age'] = 3
print(info)
增加 当字典中不存在这个键, 就会添加
info['addr'] = '鞍山市'
print(info)
删除
del info['age']
print(info)
遍历
for k, v in info.items():
print(k, '---->', v)
获取所有键
print(list(info.keys()))
获取所有的值
print(list(info.values()))
Python 中的函数
def 函数名():
函数体
def say_hello(name):
print('hello', name)
say_hello('neusoft')
1到 任意数之间累加和
def caculate_num(num):
sum_num = 0 # 存求和
for i in range(1, num+1):
sum_num = sum_num + i
return sum_num
print(caculate_num(100))
爬虫
获取到网页的源代码,requests
安装requests
import requests
获取指定域名的源代码
response = requests.get('https://www.baidu.com')
//响应状态码 200ok 404 not fount
print(response.status_code)
//响应的编码方式
//设置编码方式
response.encoding = 'utf-8'
print(response.status_code)
print(response.encoding)
// 获取响应的string类型8t
html_data = response.text
print(html_data)
// 将爬取的文件写成本地html
//文件路径,读写模式,编码方式
with open('index.html','w',encoding='utf-8') as f:
f.write(html_data)
图片的爬取
url='http://imgsrc.baidu.com/forum/pic/item/f66c34a85edf8db1051351360623dd54564e74ab.jpg'
response2=requests.get(url)
//获取byte类型的响应
img_data = response2.content
文件路径,读写模式write binary,编码方式
with open('漫画.png','wb') as f:
if response2.status_code == 200:
f.write(img_data)