0%

python日常:函数和模块的使用

引言:今日练习函数和模块的使用

函数

“代码有很多种坏味道,重复是最坏的一种!”————Martin Fowler

定义函数

计算

1
2
3
4
5
6
7
8
def factorial(num):
result = 1
for i in range(1,num+1):
result *= i
return result
n = int(input('n='))
m = int(input('m='))
print(factorial(m) // factorial(n) // factorial(n-m))

n=3
m=7
840

※注意※:
1.def定义一个方程式,def()括号里面的是自变量,定义函数结尾的return返回的值是因变量
2.Python的math模块中其实已经有一个factorial函数了,事实上要计算阶乘可以直接使用这个现成的函数而不用自己定义

函数的参数

在Python中,函数的参数可以有默认值,也支持使用可变参数,所以Python并不需要像其他语言一样支持函数的重载

1
2
3
4
5
6
7
8
9
from random import randint

def roll_dice(n=2):
total = 0
for _ in range(n):
total += randint(1, 6)
return total

print(roll_dice())

9

※注意※:
疑问:range(2)应该是range(0,2)也就是[0,1],为什么是摇两次
1.在定义函数时设定了默认值,如果再调用函数时没有传入对应参数的值,就用默认值来计算
2.可变参数的运用

举例注意1

1
2
3
4
5
6
7
8
def add(a=0, b=0, c=0):
return a + b + c

print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(c=50, a=100, b=200))

0
1
3
6
350

**※注意※:
用不同方式调用add函数,这和其他函数重载的效果一样。

可变参数

1
2
3
4
5
6
7
8
9
10
11
def add(*args):
total = 0
for val in args:
total += val
return total

print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))

0
1
3
6
25

※注意※:
1.参数名前加个*表示参数时一个可变参数

用模块管理函数

命名冲突

1
2
3
4
5
6
7
8
9
def foo():
print('hello, world!')


def foo():
print('goodbye, world!')


foo()

goodbye, world!

因为python中没有函数重载概念,所以如果两个定义名字相同,最新的定义就会覆盖掉之前的定义

解决命名冲突1

module1.py

1
2
def foo():
print('hello, world!')

module2.py

1
2
def foo():
print('goodbye, world!')

test.py

1
2
3
4
5
6
7
from module1 import foo

foo()

from module2 import foo

foo()

python中每个文件就代表一个模块(module),在使用函数的时候我们通过import关键字导入指定的模块就可以区分到底要使用的是哪个模块中的foo函数

解决命名冲突2

test.py

1
2
3
4
5
import module1 as m1
import module2 as m2

m1.foo()
m2.foo()

※注意※:
不能写成

1
2
from module1 import foo
from module2 import foo

因为程序中调用的是最后倒入的那个fo

练习

用定义函数实现计算最大公约数和最小公倍数的函数

1
2
3
4
5
6
7
8
def gcd(x, y):
(x, y) = (y, x) if x > y else (x, y)
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
return factor

def lcm(x, y):
return x * y // gcd(x, y)

写一个程序判断输入的正整数是不是回文素数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
def is_palindrome(num):
temp = num
total = 0
while temp > 0:
total = total * 10 + temp % 10
temp //= 10
return total == num

def is_prime(num):
for factor in range(2,num):
if num % factor == 0:
return False
return True if num != 1 else False

if __name__ == '__main__':
num = int(input('请输入正整数: '))
if is_palindrome(num) and is_prime(num):
print('%d是回文素数' % num)
else:
print('%d不是回文素数'% num)

※疑问※:
1.判断回文素数没看懂
2.__name__ == ‘__main__‘没看懂

变量作用域

举例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def foo():
b = 'hello'

def bar():
c = True
print(a)
print(b)
print(c)

bar()
# print(c)

if __name__ == '__main__':
a = 100
# print(b)
foo()

100
hello

※注意※:
1.foo函数里定义的b是一个局部变量,属于局部定义域;在foo函数里又定义了一个bar函数,在bar函数里,变量b就属于嵌套作用域,在bar中可以访问的到;在bar函数里又定义了一个cc只作用于bar中,其他作用关于搜不到。除了“局部作用域”、“嵌套作用域”、“全局作用域”,还有“内置作用域”。所谓的“内置作用域”就是Python内置的那些隐含标识符min、len等都属于内置作用域)。也可以在局部变量前加一个 global代表来自于全局作用域
2.在实际开发中,我们应该尽量减少对全局变量的使用,因为全局变量的作用域和影响过于广泛,可能会发生意料之外的修改和使用,除此之外全局变量比局部变量拥有更长的生命周期,可能导致对象占用的内存长时间无法被垃圾回收。事实上,减少对全局变量的使用,也是降低代码之间耦合度的一个重要举措,同时也是对迪米特法则的践行。
3.所以以后要按照以下方法书写

1
2
3
4
5
6
7
def main():
# Todo: Add your code here
pass


if __name__ == '__main__':
main()
-------------本文结束感谢您的阅读-------------
+ +