1.函数也称为方法、功能
2.函数的作用: 1、提高代码的复用性 2、让代码更简洁、简化代码 必填参数、默认值参数
3.例子
def say(): #函数名 定义函数
print('hello')#函数体
#函数不调用是不会被执行的
say() #调用函数
4.函数的参数
def calc(a,b): #形参, 形式参数
#位置参数,必填参数
res = a * b
print('%s * %s = %s'%(a,b,res))
# calc(7,8) #实参,实际参数
def op_file(file_name,conent=None): #
#默认值参数,它是非必填的
f = open(file_name,'a+',encoding='utf-8')
f.seek(0)
if conent:#不为空代表写
f.write(conent)
f.flush()
else:
all_users = f.read()
return all_users #调用完函数之后,返回什么结果
f.close() #局部变量 函数里面定义的变量,都是局部变量,只能在函数里面用,出了函数之后就不能用了。
#return
1、把函数处理的结果返回回来
2、结束函数,函数里面遇到return,函数会立即结束
# res = op_file('a.txt')
# print(res)
def haha():
#函数里面遇到return函数就立即结束了
for i in range(5):
print(i)
if i==3:
return #只写一个return的话,就返回None
res = haha()
print(res)
import string
def check(pwd):
#长度6-11
#字母和数字吧
if len(pwd)>5 and len(pwd)<12:
if set(pwd) & set(string.ascii_letters) and set(pwd) & set(string.digits): #使用&取交集
print('密码合法')
else:
print('密码不合法')
else:
print('密码不合法')
res = check('asd1234') #函数里面如果没有return的话,默认返回None res存放返回结果
print(res)
l = [1,6,8,2,4,8,9]
print(l.sort())
print(l) #return不是必须的 需要结果才写
判断小数的函数
def is_float(s):
s = str(s) #以下方法是字符串方法 所以先要转为字符串。
if s.count('.')==1:#小数点个数
s_list = s.split('.') #分割完是个list
left = s_list[0] #小数点左边
right = s_list[1] #小数点右边
if left.isdigit() and right.isdigit(): #正小数
return True
elif left.startswith('-') and left.count('-')==1 and \
left.split('-')[1].isdigit() and \ #符号分割第一个是空 所以去【1】
right.isdigit(): #判断合法负小数
return True
return False # -.1 是运算的,需要加‘’才可以
实例检查 及分析
# 1.98
# -2.50
# retrun True
# retrun False
# 1.98
# 1.98.23
# -1.90
# 需求分析:
#1、 小数点个数 .count()
# 2、按照小数点进行分割 1.98 [1,98] s.87 98.s1
#3、正小数:小数点左边是整数 右边也是整数 .isdigits()
# 负小数:小数点左边是以负号开头,但是只有一个负号,右边也是整数 -9.85
money = 500
def test(consume): # 500
return money - consume
def test1(money):
return test(money) + money
money = test1(money)
print(money)
#常量
#一个不变的值
#如果你写了一样功能,那你就要想是不是能把这个功能封装成一个函数 用大写字母定义的变量
#全局变量
公共的变量,都可以用的变量。
1、不安全,因为所有人都可以改
2、全局变量它会一直占着内存
name = '谢红'
*如果要改全局变量的话,那你要先声明一下,你修改值是全局变量
def sayName():
global name
name = '刘伟'
print('name1',name)
def lw():
age = 28
return age
def setName():
global name
name = '摸手哥'
sayName()
setName()
print('name2',name)
#数据库链接 (两种调用方式)
def op_mysql(host,port,username,password,db,charset,sql):
print('连接数据库')
op_mysql(
'192.168.1.1',
3306,'root','123456','jxz','utf-8','select') #元素意义对应
op_mysql( #根据指定的形参 入参,不用按顺序一一对应
'192.168.1.1',
db='sfsdf',
charset='sdfsdf',
sql='select * from user;'
)
# op_mysql(sql='select * from user;',
# host='192.158.11.1',
# username='sdfdsfs',
# password='sdf',
# db='sdfsdf',
# charset='sdfsdf',
# port='xx'
# )