def 定义函数
for 遍历
while 循环
if else 条件控制
默认值传参数
可变值传参
关键字传参
import calendar
def get_current_month_start_and_end(date, flag=1, message="get_current_month_start_and_end ok"):
while True:
if str(date).count('.') != 1:
raise ValueError("Pls input parameter such as '2019.05'") # 要求参数格式是:xxxx.xx,可自行设定,此处省去其他验证
year, month = str(date).split('.')[0], str(date).split('.')[1] # 分割字符串,提取年月
end = calendar.monthrange(int(year), int(month))[1] # 获取当前年月的当月天数
start_date = '%s-%s-01' % (year, month) # 第一天
end_date = '%s-%s-%s' % (year, month, end) # 最后一天
if flag - 1 < 0:
raise ValueError('error value')
print(message)
return start_date, end_date
def def_param_fun(kind, retries, arguments, **keywords):
print("def_param_fun start:", len(arguments), kind, arguments)
for index in range(len(arguments)):
if kind == arguments[index]:
print(" = index",index,kind,arguments[index])
return True
else:
print("!= index",index,kind, arguments[index])
if retries - 1 < 0:
raise ValueError('error value')
print("end-", kind)
return False
def def_param_fun2(kind, retries, *arguments, **keywords):
print("def_param_fun2 start:", len(arguments), kind, arguments)
for index in range(len(arguments)):
if kind == arguments[index]:
print(" = index",index,kind,arguments[index])
return True
else:
print("!= index",index,kind, arguments[index])
if retries - 1 < 0:
raise ValueError('error value')
print("end-", kind)
return False
# main
if __name__ == '__main__':
elp = ['aaa', 'bbb', 'ccc']
print('遍历============')
for index in range(len(elp)):
print('当前 :', elp[index])
stri = 'abcde'
for i in stri:
print(i)
count=0
print('循环============')
while(count<3):
print('一步两步')
count = count +1
if(count):
pass # 用于那些语法上必须要有什么语句,但程序什么也不做的场合.
print('默认值参数============')
print(get_current_month_start_and_end("2023.01"))
print(get_current_month_start_and_end("2023.01", 1))
# print(get_current_month_start_and_end("2023.01", 1, "sss"))
print('可变参数 ============')
# *args代表着可以传入一个list或者tuple, **args代表着可以传入一个dict
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
print(def_param_fun('Friday', 1, days))
print(def_param_fun2('Friday', 1, days))
print('关键字参数 ============')
print(get_current_month_start_and_end("2023.09", message="关键字参数"))
控制台输出值
遍历============
当前 : aaa
当前 : bbb
当前 : ccc
a
b
c
d
e
循环============
一步两步
一步两步
一步两步
默认值参数============
get_current_month_start_and_end ok
(‘2023-01-01’, ‘2023-01-31’)
get_current_month_start_and_end ok
(‘2023-01-01’, ‘2023-01-31’)
可变参数 ============
def_param_fun start: 5 Friday [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
!= index 0 Friday Monday
!= index 1 Friday Tuesday
!= index 2 Friday Wednesday
!= index 3 Friday Thursday
= index 4 Friday Friday
True
def_param_fun2 start: 1 Friday ([‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’],)
!= index 0 Friday [‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’]
end- Friday
False
关键字参数 ============
关键字参数
(‘2023-09-01’, ‘2023-09-30’)
Process finished with exit code 0
可变参数传参慎用