python 函数

#函数
def welcome():
print('欢迎你')
welcome()

def write_file(file_name,cotent):
f = open(file_name,'a+',encoding='UTF-8')
f.write(cotent)
f.seek(0)
x = f.read()
print(x)
f.close()

write_file('a.txt','今天天气好晴朗')

def op_file(file,content=None):# file为必填参数,content为可选参数
f = open(file,'a+',encoding='UTF-8')
if content:
f.write(content)
else:
f.seek(0)
return f.read()

print(op_file('1.txt'))
print('1.txt','lijun,989098')

def get_user():
name = 'xiaoming'
sex = '男'
return name,sex #返回多个值时,返回的为元祖,元祖内容无法修改

print(get_user())

#全局变量若需要修改,需要先申明
day = 1
def get_1():
global day #修改全局变量必须先申明
day = day + 1
print(day)
get_1()

l = [1,1,2,3,4,5,6,7]
for i in l:
if i % 2 != 0:
l.remove(i) #在删除了位置0的1时,位置0还是1,就忽略了未循环到
print(l)

l = [1,1,2,3,4,5,6,7]
l2 = [1,1,2,3,4,5,6,7]
for i in l2:
if i % 2 != 0:
l.remove(i) #用l2作循环,删除l,不会跳过任意值
print(l)

#因此,循环list时不要删除元素,会导致值未循环
posted @ 2019-11-16 11:12  琳淼  阅读(156)  评论(0编辑  收藏  举报