zoukankan      html  css  js  c++  java
  • python入门-函数(一)

    1定义函数并且调用  注释语句""" """

    def greet_user():
        """显示简单的问候语"""
        print("hello!")
    
    greet_user()

    2定义带参数的函数

    def greet_user(username):
        """显示简单的问候语"""
        print("hello" + username.title() + "!")
    
    greet_user('baker')

    3 形参和实参

    def describe_pet(animal_type,pet_name):
        """显示宠物信息"""
        print("
     I have a " + animal_type +".")
        print("My " + animal_type + "'s name is " + pet_name.title() + ".")
    
    describe_pet('hamster','harry')
    describe_pet('dog','willie')
    
    describe_pet(pet_name='willie',animal_type='dog')

    4  有返回值的函数

    def get_formatted_name(first_name,last_name):
        """返回整洁的名字"""
        full_name = first_name + " "+last_name
        return full_name.title()
    
    musician = get_formatted_name("jimi" , "baker")
    
    print(musician)

    5  参数可以为空的函数

    def get_formatted_name(first_name,last_name,middle_name=''):
        """返回整洁的名字"""
        if middle_name:
            full_name = first_name + " " + middle_name + " "+ last_name
        else:
            full_name = first_name + " " + last_name
    
        return full_name.title()
    
    musician = get_formatted_name('jimi','hendrix')
    print(musician)

    6 返回值可以是字典  或者列表  

    def build_person(first_name,last_name):
        """返回一个字典,其中包含一个人的信息"""
        person = {'first':first_name, 'last':last_name}
        return person
    
    musician = build_person('jimi','hendrix')
    print(musician)

    7 返回是字典,有额外的信息

    def build_person(first_name,last_name,age=''):
        """返回一个字典,其中包含一个人的信息"""
        person = {'first':first_name, 'last':last_name}
        if age:
            person['age'] = age
    
        return person
    
    musician = build_person('jimi','hendrix',age=27)
    print(musician)

    8 函数和while循环

    def get_formatted_name(first_name,last_name):
        """返回整洁的名字"""
        full_name = first_name + " " + last_name
        return full_name.title()
    
    while True:
        print("
     Please tell me your name")
        f_name = input("First name:")
        if f_name == 'q':
            break
        l_name = input("Last name:")
        if l_name == 'q':
            break
        formatted_name = get_formatted_name(f_name,l_name)
        print("
    hello," + formatted_name + "!")
  • 相关阅读:
    bzoj3524: [Poi2014]Couriers(主席树)
    51nod 1275 连续子段的差异(twopointer+单调队列)
    51nod 1274 最长递增路径(DP)
    51nod 1273 旅行计划(思维题)
    51nod 1257 背包问题 V3(分数规划)
    CSS 几款比较常用的翻转特效
    css文字飞入效果
    jQuery使用方法
    数据库
    关系型数据库基本概念及MySQL简述
  • 原文地址:https://www.cnblogs.com/baker95935/p/9283090.html
Copyright © 2011-2022 走看看