函数
使用关键字def来告诉Python你要定义一个函数。这是函数定义,向Python指出了函数名,还可能在括号内指出函数为完成其任务需要什么样的信息。
最简单的函数示例
def outprint():
print("Hello World")
outprint()
传参函数
name = input("请输入一个名字")
def outprint(name):
print("Hello , I'm " + name)
outprint(name)
name = input("请输入一个名字:")
def outprint(name):
print("Hello , I'm " + name)
outprint(name)
name = input("请输入您的姓名:")
age = input("年龄:")
sex = input("性别:")
def introduce(name,age,sex):
print(" My name is " + name)
print(" I am " + age + " years old now!")
print(" and I am a " + sex)
introduce(name,age ,sex)
关键字传参
name = input("请输入您的姓名:")
age = input("年龄:")
sex = input("性别:")
def introduce(userName,userAge,userSex):
print(" My name is " + name)
print(" I am " + age + " years old now!")
print(" and I am a " + sex)
introduce(userName = name,userAge = age , userSex = sex)
introduce(userAge = age , userName = name, userSex = sex)
introduce( userSex = sex, userName = name, userAge = age)
可见用关键字的方式调用函数可以不用考虑参数的顺序,示例代码中三种不同的调用结果都相同。
设定参数默认值
name = input("请输入您的姓名:")
def introduce(name,age = "18",sex = 'boy'):
print(" My name is " + name)
print(" I am " + age + " years old now!")
print(" and I am a " + sex)
introduce(name)
带有返回值
def sum(a,b):
return a+b
res = sum(10,23)
print(res)