english = [‘c’,‘b’,‘a’]
for e in english:
print(e)
for value in range(1,5):
print(value)
english = ['a','b','c','d']
print(english[0:3]) #输出0,1,2前包含后不包含
也可以这样english[:3] #当前者为0时直接写后边的
还可以这样english[2:] #从索引为2到最后
居然还能这样english[:] #复制当前列表,将原有的list副本存储到新的列表地址下
– 在Python中,False,0,’’,[],{},()都可以视为假
if 1 == 1 :
print('对')
else :
print('错')
age = 12
if age < 4:
print('your admission cost is 0')
if age < 18:
print('your admission cost is 5')
dict = {}
dict['name']='json'
dict['length']=30;
dict = {'name':'json','length':30,'age':'12'}
for key,value in dict.items():
print('key:'+key+'value'+value)
index = 1
while index <= 10:
print(index)
index++
while 'a' in english:
english.remove('a')
小结:python中while和java差不多,只是语法格式的改变
## 定义函数,以def开头,括号中直接放参数名
def greet_user(username):
print("Hello, "+ username.title() + "!")
greet_user('Yunpeng.Gu')
位置实参:
def describe_pet(animal_type,pet_name):
···
关键字实参:
def describe_pet(animal_type,pet_name):
···
默认值:
def describe_pet(pet_name,animal_type="dog"):
···
describe_pet(pet_name=‘harry’) 或者describe_pet(‘harry’)
使用return 返回,可以返回各种类型而且不用提前声明
def get_formatted_name(first_name,last_name):
## 返回字符串
full_name = first_name + " " + last_name
return full_name.title()
## 返回字典
full_name = {'first_name':first_name,'last_name':last_name}
return full_name
····
def function_name(*value):
···
*是python来创造一个空元组,并将收到的值都封装到元组里
如果同时存在其他参数,应把可变参数放到最后且只能有一个可变参数
可变关键字参数:
使用**作为前缀
def build_profile(first,last,**user_info):
···
profile={}
for key,value in user_info.items():
profile[key]=value
build_profile('gu','yunpeng',location='beijing',age=21,sex='man')
一个py文件就是一个模块
导入模块就是Python解释器打开模块文件然后复制导入的代码
import module_name
## 别名,如果起了别名必须使用别名
import module_name mn
from module_name import function_name
## 别名,如果起了别名必须使用别名
from module_name import function_name as fn
## 一次导入多个函数并起别名
from module_name import function_name1 as fn1,function_name2 as fn2
from module_name import *
## 如果Python遇到同名函数将会覆盖所以一般不使用这种方法
def __init__(self,name,age):
self.name = name
self.age = age
init()方法,构造方法,必须声明self而且必须在其他参数之前,当创建类的实例时都会运行该方法
继承:
class ClassName(SuperClass):
def __init__(self,name,age,sex):
## 初始化父类时不需要传入self
super().__init__(name,age,sex)
with open('pi.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
逐行读取
with open('pi.txt') as file_object:
for line in file_object:
print(line)
写文件
with open(path_prefix+"file_write.txt",'w') as file_writer:
name = input("Please Enter Your Name: ")
file_writer.write(name)
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(answer)
import json
numbers = [1,3,5,1,2]
with open(filename,'w') as file_obj:
json.dump(numbers,f_obj)
将数据以json形式写入文件
with open(filename,'r') as f_obj:
json.load(f_obj)
将数据以json类型解析出来
python小结:python的话还是以后有机会用来造数或者爬虫的话吧,毕竟对python的第三方库不是那么习惯,用起来效率可能不高
1.写文件
1.1 普通写入
with open('../config/data.csv', 'w') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(['id', 'name', 'age']) #写表头
writer.writerow(['1001', '张三', '22']) #写内容
1.2 指定分隔符
with open('../config/data.csv', 'w') as csvfile:
writer = csv.writer(csvfile,delimiter = '#')
writer.writerow(['id', 'name', 'age']) #写表头
writer.writerow(['1001', '张三', '22']) #写内容
1.3 同时写入多行
with open('../config/data.csv', 'w') as csvfile:
writer = csv.writer(csvfile,delimiter = '#')
writer.writerows([['id', 'name', 'age'],['1001', '张三', '22'],['1001', '王五', '23'],['1001', '李四', '21']])
1.4 写入字典内容
with open('data.csv','w') as csvfile:
fieldnames = ['id','name','age'] #指定表头
writer = csv.DictWriter(csvfile,fieldnames=fieldnames) #配置表头
writer.writeheader() #写入表头到文件中
writer.writerow({'id':'1001','name':'mike','age':'11'}) #写入内容
2 读文件
2.1 使用pandas库进行解析csv
df = pd.read_csv('../config/data.csv',encoding='gbk') print(df)
import pymysql
# 连接到mysql
db = pymysql.connect(host='localhost',user='root',password='root',port=3306)
# 获取游标
cursor = db.cursor()
# 执行sql语句
cursor.execute('select 1 from dual')
# 关闭数据库连接
db.close()
try:
cursor.execute(sql)
db.commit()
except:
db.rollback()
import pymongo
client = pymongo.MongoClient(host='localhost',port=27017)
# 或者client = MongoClient('mongodb://localhost:27017/')
db = client.test
# 或者db = client['test']
collection = db.students
collection = db['students']
student = {
'id':'1001',
'name':'李四'
}
result = collection.inset(student)