函数定义和简单调用
公司新来部分新员工,定义函数并循环打印欢迎新员工的消息
employees = {"Chris": "NOC", "David": "PJM", "Brain": "SA", "John": "UX"} def introduce_employee(employee, post): print("Welcome our new colleague " + username + ", his post is " + job + " !") for key, value in employees.items(): username = key job = value introduce_employee(username, job)
输出
Welcome our new colleague Chris, his post is NOC ! Welcome our new colleague David, his post is PJM ! Welcome our new colleague Brain, his post is SA ! Welcome our new colleague John, his post is UX !
函数使用默认值
def print_employees(employee, post="NOC"): print("Welcome our new colleague " + employee + ", his post is " + post + ".") print_employees("David", "UX") print_employees("Chris", "PJM") print_employees("Brain") print_employees("John")
输出
Welcome our new colleague David, his post is UX. Welcome our new colleague Chris, his post is PJM. Welcome our new colleague Brain, his post is NOC. Welcome our new colleague John, his post is NOC.
使用return返回值
def employees(username, post): employee_info = "Welcome our new colleague " + username + ", his post is " + post + " !" return employee_info employee = employees("Chris", "NOC") print(employee)
输出
Welcome our new colleague Chris, his post is NOC !
借助函数和while循环打印欢迎用户信息
def get_full_name(first_name, last_name): full_name = first_name + "." + last_name return full_name.title() while True: f_name = input("Please input your first name: ") if f_name == "quit": print("Since you input '%s' as first name, will cancel and exit..." % f_name) break l_name = input("Please input your last name: ") if l_name == "quit": print("Since you input '%s' as last name, will cancel and exit..." % l_name) break format_name = get_full_name(f_name, l_name) print("Hello %s." % format_name)
输出
Please input your first name: zhang Please input your last name: lei Hello Zhang.Lei. Please input your first name: tian Please input your last name: liang Hello Tian.Liang. Please input your first name: quit Since you input 'quit' as first name, will cancel and exit...
列表和函数循环使用
def print_cars(cars): for car in cars: print(car.title() + " is Japan automobile brand.") car_list = {'toyota', 'honda', 'mazda', 'nissan'} print_cars(car_list)
输出
Mazda is Japan automobile brand. Toyota is Japan automobile brand. Honda is Japan automobile brand. Nissan is Japan automobile brand.
输入任意数量的实参
def print_cars(*cars): for car in cars: print(car.title() + " is Japan automobile brand.") print_cars("toyota") print_cars('toyota', 'honda', 'mazda', 'nissan')
输出
Toyota is Japan automobile brand. Toyota is Japan automobile brand. Honda is Japan automobile brand. Mazda is Japan automobile brand. Nissan is Japan automobile brand.
===================来自一泽涟漪的博客,转载请标明出处 www.cnblogs.com/ilifeilong===================