divmod
divmod(a,b)方法返回的是a/b(取整)以及a对b的余数
例如:
divmod(4,3)返回的结果是(1,1)
join
str.join(sequence)
sequence – 要连接的元素序列。
str = “-”;
seq = (“a”, “b”, “c”); # 字符串序列
print str.join( seq );
以上实例输出结果如下:
a-b-c
函数应用实例
# coding=utf-8
# 输入一个正整数
x = int(input())
# 请在此添加代码,将输入的一个正整数分解质因数
########## Begin ##########
def factor(x):
if x == 1:
return []
else:
for i in range(2, x + 1):
n, d = divmod(x, i)
if d == 0:
return [i] + factor(n) # 采用递归的方式
result = factor(x)
########## End ##########
# 输出结果,利用map()函数将结果按照规定字符串格式输出
print(x,'=','*'.join(map(str,result)))
index
List = [1, 2, 3, 6]
print("索引位置: ", List.index(1))
索引位置: 0
print("索引位置: ", List.index(6))
索引位置: 3
python 中describe()
seek方法
PyMySQL使用
1.python链接数据库
conn = pymysql.connect(host=‘127.0.0.1’, user=‘root’, password=‘', database=‘authoritydb’)
conn = pymysql.connect(‘127.0.0.1’, ‘root’, '’, ‘authoritydb’)
3.执行sql语句
cursor.execute(sql)
4.# 关闭游标
cursor.close()
# 关闭连接
conn.close()
- 查询数据
cursor.execute(“select * from user where id<=5 ORDER BY id DESC”)
pymysql中获取数据常用的有2个函数,分别是:fetchall()返回所有记录,fetchone()返回单条记录。以及一个只读属性rowcount并返回执行execute()方法后受影响的行数
数据库中有where字句,返回当where条件成立的数据
关于order by,常用于对数据进行排序常用值有2个desc表示降序排列,asc表示升序排列
fetchone()返回单条记录
cursor.execute(“select * from user where id<=5 ORDER BY id DESC”)
i=0
for i in range(5):
res = cursor.fetchone()
print(res)
(5, ‘teble4’, ‘teble4’)
(4, ‘teble3’, ‘teble3’)
(3, ‘teble2’, ‘teble2’)
(2, ‘teble1’, ‘teble1’)
(1, ‘teble0’, ‘teble0’)
fetchall()返回所有记录
((4, ‘长沙’), (3, ‘北京’), (2, ‘北京’), (1, ‘北京’))
6.修改数据
修改user表中username=teble0的数据为username字段为root以及password字段为root。
cursor.execute(“update user set username = ‘root’, password = ‘root’ WHERE username = ‘teble0’”)
7.删除数据
删除user表中username=teble1的数据。
cursor.execute(“delete from user where username=‘teble1’”)
注意’‘ 单引号的使用
基本上大多数sql语句需要用单引号
包括python链接mysql 的密码即使是数字也需要单引号包裹