day05函数、集合、random模块

1.函数

  1)位置参数

def my(name,sex):
#调用函数时位置参数是必填的
return name,sex
print(my()) #如果不传值时会报错


2)默认参数及默认参数的使用
def db_connect(ip,port=3306): #port=3306给默认参数赋值
return print(ip,port)
db_connect("192.0.0.1") #调用函数不给默认参数传值时,不会报错,会使用默认值
db_connect("192.0.0.1",3307)

默认参数练习:
import  json

# 写一个函数,如果传入的dic不为空时,写入文件,如果传入的dic为空,读文件
def op_file(filename,dic=None):
if dic:
with open(filename,'w',encoding="utf-8") as f1:
json.dump(dic,f,ensure_ascii=False)

else:
with open(filename,encoding="utf-8") as f2:
content=f2.read()
if content:
reg=json.load(content)
else:
reg={}
return reg
3)return的作用
#return的作用 1.结束函数,只要遇到return函数结束 2.返回函数结果
def my():
for i in range(50):
return i
print(my()) #只返回一个值 0

4)写一个函数,校验传入的参数是否是小数
思路:1)传入的参数必须是数字
2)传入的参数必须有且只有一个小数点
3)如果参数的参数时负小数必须满足条件1和条件2,并且只以一个负号开头
def jy_xiaoshu(num):
num=str(num)
if num.count(".")==1:
a,b=num.split(".")
# print(type(a),b)
if a.isdigit() and b.isdigit():

print("是正小数")
elif a.startswith("-") and a[1:].isdigit() and b.isdigit():

print("是负小数")

# else: # 使用else时,如果传入的值时"--10.3",返回的是“” ,当传入10a.3返回也是空
# else:
return print("传入不是小数")
jy_xiaoshu("---10.3")

5)全局变量
































猜你喜欢

转载自www.cnblogs.com/zzzao/p/9638058.html