当前位置:网站首页>Use of Day6 functions and modules
Use of Day6 functions and modules
2022-07-28 02:26:00 【Sumarua】
Use of functions and modules
Before I explain the contents of this chapter , Let's study a math problem first , Please say how many sets of positive integer solutions are there in the following equation .

in fact , The above question equates to 8 Each apple is divided into four groups. How many schemes does each apple have . The answer to this question comes to mind .

It can be used Python To calculate this value , The code is as follows .
"""
Input M and N Calculation C(M,N)
"""
m = int(input('m = '))
n = int(input('n = '))
fm = 1
for num in range(1, m + 1):
fm *= num
fn = 1
for num in range(1, n + 1):
fn *= num
fm_n = 1
for num in range(1, m - n + 1):
fm_n *= num
print(fm // fn // fm_n)
Function function
I wonder if you have noticed , In the code above , We did 3 Second factorial , Such code is actually repetitive code . Master programmer Martin Fowler Sir once said :“ Code has a lot of bad taste , Repetition is the worst !”, To write high-quality code, the first thing to solve is to repeat the code . For the code above , We can encapsulate the function of calculating factorials into a function called “ function ” In the function module of , Where factorials need to be calculated , We just need “ call ” This “ function ” That's all right. .
Defined function
stay Python Can be used in def Keyword to define the function , Like variables, every function has a loud name , And the naming rules are consistent with the variable naming rules . You can place the parameters passed to the function in parentheses after the function name , This is very similar to the mathematical function , The parameter of function in the program is equal to the argument of function in mathematics , And after the function is executed, we can use return Keyword to return a value , This is equivalent to the dependent variable of the function in mathematics .
After learning how to define functions , We can refactor the above code , The so-called refactoring is to adjust the code structure without affecting the code execution result , The code after refactoring is as follows .
"""
Input M and N Calculation C(M,N)
"""
def fac(num):
""" Find the factorial """
result = 1
for n in range(1, num + 1):
result *= n
return result
m = int(input('m = '))
n = int(input('n = '))
# When you need to calculate factorial, you don't need to write a loop to find factorial, but directly call the defined function
print(fac(m) // fac(n) // fac(m - n))
explain : Python Of
mathThere is already a module namedfactorialFunction implements factorial operation , In fact, you don't have to define your own function to find factorial . In the following example , The function we are talking about is Python The standard library has been implemented , We are here to explain the definition and use of functions to implement them again , This kind of low-level repetitive work is not recommended in actual development .
The parameters of the function
Function is a code supported in most programming languages " Building blocks ", however Python There are many differences between functions in and other languages , One of the significant differences is Python The treatment of function parameters . stay Python in , Function parameters can have default values , Variable parameters are also supported , therefore Python It doesn't need to be supported like any other language Function overloading , Because we can define a function in many different ways , Here are two small examples .
from random import randint
def roll_dice(n=2):
""" Shaker """
total = 0
for _ in range(n):
total += randint(1, 6)
return total
def add(a=0, b=0, c=0):
""" Add three numbers """
return a + b + c
# If no parameter is specified, then use the default value to shake two dice
print(roll_dice())
# Shake three dices
print(roll_dice(3))
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
# Parameters can be passed in different order
print(add(c=50, a=100, b=200))
We set the default values for the parameters of both functions , This also means that if the function is called without passing in the value of the corresponding parameter, the default value of the parameter will be used , So in the above code, we can call it in various ways add function , This is consistent with the effect of function overloading in many other languages .
In fact, the above add There's a better way to implement functions , Because we may be right about 0 Add with one or more parameters , How many parameters are determined by the caller , We as function designers know nothing about this , So when the number of parameters is uncertain , We can use variable parameters , The code is as follows .
# Before the parameter name * Express args Is a variable parameter
def add(*args):
total = 0
for val in args:
total += val
return total
# Calling add Function can be passed in 0 Two or more parameters
print(add())
print(add(1))
print(add(1, 2))
print(add(1, 2, 3))
print(add(1, 3, 5, 7, 9))
Use modules to manage functions
For any programming language , To the variable 、 It's a headache to name identifiers like functions , Because we will encounter the awkward situation of naming conflict . The simplest scenario is in the same .py Two functions with the same name are defined in the file , because Python There is no concept of function overloading , Then the later definition will overwrite the previous one , This means that only one function with the same name exists .
def foo():
print('hello, world!')
def foo():
print('goodbye, world!')
# What will the following code output ?
foo()
Of course, we can easily avoid the above situation , But if the project is developed by a team of multiple people , There may be multiple programmers on the team who have a definition called foo Function of , So how to solve this naming conflict ? The answer is simple ,Python Each file in represents a module (module), We can have functions of the same name in different modules , When we use functions, we pass through import Keyword import can distinguish which module to use foo function , The code is as follows .
module1.py
def foo():
print('hello, world!')
module2.py
def foo():
print('goodbye, world!')
test.py
from module1 import foo
# Output hello, world!
foo()
from module2 import foo
# Output goodbye, world!
foo()
You can also distinguish which one to use as follows foo function .
test.py
import module1 as m1
import module2 as m2
m1.foo()
m2.foo()
But if you write the code as follows , So the program calls the last imported one foo, Because it was imported later foo Overwrite the previously imported foo.
test.py
from module1 import foo
from module2 import foo
# Output goodbye, world!
foo()
test.py
from module2 import foo
from module1 import foo
# Output hello, world!
foo()
It should be noted that , If the module we import has executable code besides defining functions , that Python The interpreter will execute the code when importing the module , In fact, we may not want to , So if we write execution code in the module , It's best to put the execution code in the conditions shown below , In this case, unless you run the module directly ,if The code will not execute under the condition , Because only the name of the directly executed module is "__main__".
module3.py
def foo():
pass
def bar():
pass
# __name__ yes Python An implicit variable in represents the name of the module
# Only by Python The name of the module directly executed by the interpreter is __main__
if __name__ == '__main__':
print('call foo()')
foo()
print('call bar()')
bar()
test.py
import module3
# Import module3 when Will not execute in module if The code when the condition holds Because the name of the module is module3 instead of __main__
practice
practice 1: Realize the function of calculating the maximum common divisor and the minimum common multiple .
Refer to the answer :
def gcd(x, y):
""" Find the greatest common divisor """
(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):
""" Find the least common multiple """
return x * y // gcd(x, y)
practice 2: To realize the function of judging whether a number is a palindrome number .
Refer to the answer :
def is_palindrome(num):
""" Judge whether a number is palindrome number """
temp = num
total = 0
while temp > 0:
total = total * 10 + temp % 10
temp //= 10
return total == num
practice 3: To realize the function of judging whether a number is a prime number .
Refer to the answer :
def is_prime(num):
""" Judge whether a number is a prime """
for factor in range(2, int(num ** 0.5) + 1):
if num % factor == 0:
return False
return True if num != 1 else False
practice 4: Write a program to determine whether the input positive integer is a palindrome prime number .
Refer to the answer :
if __name__ == '__main__':
num = int(input(' Please enter a positive integer : '))
if is_palindrome(num) and is_prime(num):
print('%d It's palindrome prime number ' % num)
Be careful : As can be seen from the above procedure , When we Extract the repeated and relatively independent functions in the code into functions after , We can Combine these functions To solve more complex problems , That's a very important reason why we define and use functions .
Scope of variable
Last , Let's talk about it Python The problem of variable scope in .
def foo():
b = 'hello'
# Python You can define functions inside functions
def bar():
c = True
print(a)
print(b)
print(c)
bar()
# print(c) # NameError: name 'c' is not defined
if __name__ == '__main__':
a = 100
# print(b) # NameError: name 'b' is not defined
foo()
The above code can be successfully executed and printed out 100、hello and True, But we noticed , stay bar There is no definition inside the function a and b Two variables , that a and b Where did it come from . We code in the above if A variable is defined in the branch a, This is a global variable (global variable), Belongs to the global scope , Because it's not defined in any function . Above foo We define variables in functions b, This is a local variable defined in a function (local variable), It's part of the local scope , stay foo It's not accessible outside of the function ; But for the foo intra-function bar In terms of functions , Variable b Belongs to nested scope , stay bar We can access it in the function .bar Variables in functions c It's part of the local scope , stay bar Functions are not accessible . in fact ,Python When looking for a variable, it will follow “ Local scope ”、“ Nested scope ”、“ Global scope ” and “ Built-in scope ” Search in order , The first three we've seen in the code above , So-called “ Built-in scope ” Namely Python Built in identifiers , We used it before input、print、int Etc. are built-in scopes .
Take a look at the following code , We want to modify global variables through function calls a Value , But in fact, the following code can't do .
def foo():
a = 200
print(a) # 200
if __name__ == '__main__':
a = 100
foo()
print(a) # 100
Calling foo After the function , We found that a The value of is still 100, This is because when we are in function foo Write in a = 200 When , Is to redefine a name as a Local variables of , It has a global scope a It's not the same variable , Because the local scope has its own variable a, therefore foo Function no longer searches for a. If we wish in foo Function to modify... In the global scope a, The code is as follows .
def foo():
global a
a = 200
print(a) # 200
if __name__ == '__main__':
a = 100
foo()
print(a) # 200
We can use global Keyword to indicate foo Variables in functions a From the global scope , If there is no a, Then the next line of code will define variables a And put it in the global scope . Empathy , If we want functions inside functions to modify variables in nested scopes , have access to nonlocal Keyword to indicate that the variable is from a nested scope , Please test yourself .
In actual development , We should minimize the use of global variables , Because the scope and influence of global variables are too wide , Unexpected modification and use may occur , In addition, global variables have a longer life cycle than local variables , It may cause the memory occupied by the object to be unavailable for a long time Garbage collection . in fact , Reduce use of global variables , It is also an important measure to reduce the coupling between codes , It's also right Dimitar's law Practice of . Reducing the use of global variables means that we should try to keep the scope of variables within the function , But if we want to extend the life cycle of a local variable , So that it can still use its value after the function call that defines it , You need to use Closure , We will explain this in the following content .
explain : A lot of people will often “ Closure ” and “ Anonymous functions ” Confuse STH with STH else , But actually they are not the same thing , If you want to understand this concept , You can see Wikipedia Explanation of or You know Discussion on this concept .
Said so much , In fact, the conclusion is very simple , From now on we can put Python The code is written in the following format , This little improvement is actually a huge step based on our understanding of functions and scopes .
def main():
# Todo: Add your code here
pass
if __name__ == '__main__':
main()
边栏推荐
- Sample imbalance - entry 0
- This operation may not be worth money, but it is worth learning | [batch cutting of pictures]
- [Star Project] small hat aircraft War (VI)
- Unittest单元测试框架全栈知识
- C#引入WINAPI传递中文字符串参数字符集问题
- Plato Farm在Elephant Swap上铸造的ePLATO是什么?
- Unity saves pictures to albums and rights management
- Digital empowerment and innovation in the future: hese eredi appears at the 5th Digital China Construction Summit
- ArcGIS: loading historical remote sensing images
- 清除浮动的原因和六种方法(解决浮动飞起影响父元素和全局的问题)
猜你喜欢

Common problem types and methods of mathematical univariate differential proof problems in postgraduate entrance examination

Structure pseudo class selector - find single - find multiple - nth of type and pseudo elements
![[advanced ROS chapter] Lecture 10 gadf integrated simulation process and examples based on gazebo](/img/d0/5fa2ae7fc7866b7a55cf103da4519d.png)
[advanced ROS chapter] Lecture 10 gadf integrated simulation process and examples based on gazebo

What is eplato cast by Plato farm on elephant swap?

Huawei app UI automation test post interview real questions, real interview experience.

11-Django-基础篇-数据库操作

微信小程序实现动态横向步骤条的两种方式

使用BigDecimal类型应该避免哪些问题?(荣耀典藏版)

Read Plato & nbsp; Eplato of farm and the reasons for its high premium

How to put app on the app store?
随机推荐
CeresDAO:全球首个基于DAO赋能Web3.0的去中心化数字资产管理协议
Day6 函数和模块的使用
Appium click operation sorting
获取两个集合相差数据
In practical work, how do I use postman for interface testing?
They are all talking about Devops. Do you really understand it?
微信小程序实现动态横向步骤条的两种方式
Promise from introduction to mastery (Chapter 2 understanding and use of promise)
Leetcode hot topic Hot 100 - > 3. longest substring without repeated characters
Promise从入门到精通 (第1章 Promise的介绍和基本使用)
Codeforces Round #807 (Div. 2) A-C题解
小程序毕设作品之微信校园浴室预约小程序毕业设计成品(2)小程序功能
使用BigDecimal类型应该避免哪些问题?(荣耀典藏版)
了解加密行业的“下一个大趋势”——Ventures DAO
MySQL high availability and master-slave synchronization
[Yugong series] use of tabby integrated terminal in July 2022
Important arrangements - the follow-up live broadcast of dx12 engine development course will be held at station B
Clear the cause of floating and six methods (solve the problem that floating affects the parent element and the global)
【HCIP】BGP 基础
组原必备知识点