Python入门(04) -- 函数

一、定义函数

使用函数打印hello world

def say_hello():
    print('Hello world!')
say_hello()

打印结果:

Hello world!

1.向函数传递信息

def say_hello(person_name):
    print("Nice to meet you, " + person_name + "!")
say_hello("Jhon")
Nice to meet you, Jhon!

二、传递实参

1.位置实参

def say_hello(first_name, last_name):
    print("Hello, " + first_name.title() + " " + last_name.title())
say_hello('zhang', 'san')

打印结果:

Hello, Zhang San

2.关键字实参

def say_hello(first_name, last_name):
    print("Hello, " + first_name.title() + " " + last_name.title())
say_hello(first_name = 'zhang', last_name = 'san')

打印结果:

Hello, Zhang San

3.默认值

def say_hello(first_name, last_name, middle_name = ''):
    print("Hello, " + first_name.title() + " " 
          + last_name.title()) + middle_name
say_hello('zhang', 'san')

打印结果:

Hello, Zhang San

三、返回值

1.返回简单值

def say_hello(first_name, last_name):
    return "Hello, " + first_name.title() + " " + last_name.title()
print(say_hello('zhang', 'san'))

打印结果:

Hello, Zhang San

2.返回字典

def build_person(first_name, last_name):
    person = {'first_name': first_name, 'last_name': last_name}
    return person
build_person('zhang', 'san')
print(build_person('zhang', 'san'))

打印结果:

{'first_name': 'zhang', 'last_name': 'san'}

四、传递列表

def say_hello(names):
    for name in names:
        msg = "Hello, " + name.title() + "!"
        print(msg)
people = ['jhon', 'lili', 'james']
say_hello(people)

打印结果:

Hello, Jhon!
Hello, Lili!
Hello, James!

五、传递任意数量的实参

def say_hello(*names):
    print(names)
say_hello('zhao', 'qian', 'sun')

打印结果:

('zhao', 'qian', 'sun')

1.结合使用位置实参和任意数量实参

def say_hello(age, *names):
    print("Age :" + str(age))
    for name in names:
        print("- Name: " + name)
say_hello(12, 'zhao', 'qian', 'sun')

打印结果:

Age :12
- Name: zhao
- Name: qian
- Name: sun
posted @ 2020-01-18 09:03  那人_那事  阅读(130)  评论(0编辑  收藏  举报