第一题:函数内修改同名全局变量需要使用global关键字进行声明,否则报错:UnboundLocalError
# python在局部不可以改变全局变量,编译不通过
num = 1
def fn():
global num
num += 1
return lambda:print(num)
x = fn()
x() #------->2
第二题:join()将两个字符串用指定的符号连接成新的字符串
res = []
for i in 'python':
if i == 'h':
continue
res.append(i)
print(res)#----------->['p', 'y', 't', 'o', 'n']
print(' '.join(res))#------->p y t o n
print(','.join(res))#-------->p,y,t,o,n
第三题:第一次遇见sort带参数的用法
list = ['apple','lemon','pear','peach']
def fn(x):
return x[::-1]
list.sort(key = fn,reverse = True)
print(list)#------->['pear', 'lemon', 'peach', 'apple']
第四题:mysql连接数据库
mydb = mysql.connector.connect(
host = "locasthost",
user = "root",
passwd = "123456",
database = "test"
)
# 获取游标操作
mycursor = mydb.cursor()
mycursor.excute("select * from users")
myresult = mycursor.fetchall()
print(myresult)
第五题
counter = 1
def dolotsofstuff():
global counter
for i in(1,2,3):
counter += 1
dolotsofstuff()
print(counter)#-------------->4
第六题
t1 = (1,2,3) t2 = t1[:] print(t1 is t2)#---------->True list1 = [1,2,3] list2 = list[:] print(id(list1)==id(list2))#---------->False s1 ='123' s2 = '123' print(s1 is s2)#---------->True a = 123 b = 123 print(a is b)#---------->True



