函数(方法)的定义:封装了能够实现某种特定功能的程序;
函数(方法)的作用:便于代码的调用和维护,复用性强;
#def 里面的代码只是用来调用的,只有当你调用它的时候才会运行
#语法
def function_name():
pass #占位符
方法体
#定义函数
def helloWord():
print('hello Python')
#使用函数
helloword()
运行函数的主入口,相当于java中main方法:
一般在一个类的最下方
if __name__ == "__main__":
#打印99乘法表
def cfb():
for i in range(1, 10):
for j in range(1, i + 1):
print(j, '*', i, '=', j * i, end='\t')
print()
#输入三个数字,判断是否可以组成三角形
def isTriangle(n1,n2,n3):
if type(n1) == type(1) and type(n2) == type(1) and type(n3) == type(1):
if n1 + n2 > n3 and n2 + n3 > n1 and n3 + n1 > n2 and n1 > 0 and n2 > 0 and n3 > 0:
print('可以组成三角形')
else:
print('不可以组成三角形')
else:
print('error')
# 登陆
def login(username,password):
if type(username) == type('a') and type(password) == type('a'):
if username == 'admin' and password == 'admin':
# print('登陆成功')
return 'login success'
elif username != 'admin' and password == 'admin':
# print('uaername错误')
return 'username error'
elif username == 'admin' and password != 'admin':
# print('password错误')
return 'password error'
else:
# print('username和password错误')
return 'uaername and password error'
else:
# print('error:格式错误')
return 'error'
# 列表 字典 字符串 -清空 数字-变为0
def again_assignment(a):
if type(a) == type([1]) or type(a) == type({'a':1}):
a.clear()
if type(a) == type('a'):
a = ''
if type(a) == type(1):
a = 0
return a
# 运行函数的主入口 相当于main方法
if __name__ == "__main__":
helloWord()
cfb()
isTriangle(n1 = 3,n2 = 4,n3 = 5)
login_Result = login('admin','admin')
print(login_Result)
new_data =again_assignment({'a':1})
print(new_data)