lhl
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
首页
python
leetcode
产品思想
软件测试
博客 (opens new window)
github (opens new window)
  • python

    • Python 基础

      • 数据结构
      • 函数
        • 函数
      • 异常
      • 控制语句
      • 运算符
      • 模块
      • 输入输出
      • json
    • Python 数据库

    • 面向对象

    • Python Web

    • Python 进阶

  • leetcode

  • 软件测试

  • Git

  • linux

  • 产品

  • MySql

  • docker

  • python
  • 基础
2023-04-28
目录

函数

# 函数

# 函数定义

函数通过关键字 def

## 函数定义
def say_hello():
    print('hello function')


## 函数调用
say_hello()

# 函数参数

在定义函数 时给定的名称称作_“形参”(Parameters),在调用函数时你所提供给函数的值称作“实 参”_(Arguments)。

def print_max(a, b):
    if (a > b):
        print(a)
    elif (b > a):
        print(b)
    else:
        print("%d, %d" % (a, b))


print_max(3, 5)
print_max(5, 3)
print_max(5, 5)

x = 4
y = 6
print_max(x, y)

# 局部变量

def func_local(x):
    print('x is now, %d' % x)
    x = 30
    print('x in function now, %d' % x)


x = 50
func_local(x)
print('x out of function, %d' % x)

# global全局变量

x = 50


def func_global():
    global x
    print('global x is %d' % x)
    x = 30
    print('global x is %d' % x)


func_global()
print('global x is %d, out of function' % x)

# 默认参数

def func_default(message, time=1):
    print(message * time)


func_default('hello')	
func_default('hello world', 5)

def func_default(message, time=1): , func_default('hello')如果没给实参, 那么time 就会有默认值

# 关键字参数


def func_kw(a, b=3, c=1):
    print('a is', a, 'b is', b, 'c is', c)


func_kw(3, 7)
func_kw(2, c=5)
func_kw(c=50, a=100)

# 可变参数

def func_var(a=5, *numbers, **phonebooks):
    print('a', a)
    for i in numbers:
        print('numbers,', i)
    print('phonebooks')
    for k, v in phonebooks.items():
        print('k:', k, 'v:', v)

##  1,2,3 会形成元组,填入 number
## Jack=1123, John=2231, Inge=1560 会形成字典, 填入phonebooks
func_var(10, 1, 2, 3, Jack=1123, John=2231, Inge=1560)

# 返回值

def maximum(x, y):
    if x > y:
        return x
    elif x == y:
        print('x ==y')
    else:
        return y


print(maximum(23, 42))
print(maximum(42, 23))
print(maximum(42, 42))

如果 return 语句没有搭配任何一个值则代表着 返回 None 。 None 在 Python 中一 个特殊的类型,代表着虚无。举个例子, 它用于指示一个变量没有值,如果有值则它的值便 是 None(虚无) 。 每一个函数都在其末尾隐含了一句 return None ,除非你写了你自己的 return 语句。

# docstring


def maximum(x, y):
    """

    :param x:
    :param y:
    :return: 两数较大值,返回None
    """
    if x > y:
        return x
    elif x == y:
        print('x ==y')
    else:
        return y


print(maximum(23, 42))
print(maximum(42, 23))
print(maximum(42, 42))
print(maximum.__doc__)

数据结构
异常

← 数据结构 异常→

最近更新
01
lhl learn notes
02
filter
06-09
03
decorator
06-09
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式