Python从零学起

[Python学习路线]--Python基础no.05

2019-04-27  本文已影响0人  FANGQI777

回顾前一节内容,前一节主要对txt文件进行了操作。之后的程序应该去网上搜索针对excel,python的处理。excel脚本化处理还是可以在日常生活中节省很多时间的。本次学习的目标,了解掌握python中基本的函数,以及函数中的简单注意事项。

1. 函数

python中的函数用def来定义,可以有返回值,也可以无返回值。

下面写一段简单的代码测试一下函数是如何接收参数、使用参数的:

def print_two(arg1, arg2):
    print(f"arg1: {arg1}, arg2: {arg2}")


def print_two_again(*args):
    arg1, arg2 = args
    print(f"arg1: {arg1}, arg2: {arg2}")


def print_one(arg1):
    print(f"arg1: {arg1}")


def print_none():
    print("This function got nothing")


print_two("QI", "FANG")
print_two_again("QI", "FANG")
print_one("QI")
print_none()

运行结果:

FANGQIdeMacBook-Pro:PythonStudy fangqi$ python3 ex14.py 
arg1: QI, arg2: FANG
arg1: QI, arg2: FANG
arg1: QI
This function got nothing

2. 有返回值的函数

# 带返回值的函数


def add(x, y):
    print(f"Adding {x} + {y}")
    return x + y


def subtract(x, y):
    print(f"Subtracting {x} - {y}")
    return x - y


def multiply(x, y):
    print(f"Multiplying {x} * {y}")
    return x * y


def divide(x, y):
    print(f"Dividing {x} / {y}")
    return x / y


print("Let's do some mathematical calculation with just function!")

a = add(5, 5)
b = subtract(5, 5)
c = multiply(5, 5)
d = divide(5, 5)

print(f"a: {a}, b: {b}, c: {c}, d: {d}")

python 中的变量不用预先定义, 可以直接做接收。

deMacBook-Pro:PythonStudy fangqi$ python3 ex15.py
Let's do some mathematical calculation with just function!
Adding 5 + 5
Subtracting 5 - 5
Multiplying 5 * 5
Dividing 5 / 5
a: 10, b: 0, c: 25, d: 1.0
上一篇下一篇

猜你喜欢

热点阅读