程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] function topic (knowledge summary, exercise refinement and programming practice)

編輯:Python

Personal home page : Huang Xiaohuang's blog home page
Stand by me : give the thumbs-up Collection Focus on
Maxim : Only one step at a time can we accept the so-called luck

This article is from the column :Python Basic course
Welcome to the support subscription column ️

List of articles

  • 1 Function introduction and quick start
  • 2 Function USES
    • 2.1 Function definition and description
    • 2.2 Documentation notes for functions
    • 2.3 The parameters of the function
    • 2.4 The return value of the function
    • 2.5 Nested calls to functions
  • 3 Function specific training
    • 3.1 Fibonacci sequence
    • 3.2 Prime judgment
    • 3.3 Twin prime number
    • 3.4 Temperature conversion
    • 3.5 Bean pile problem
  • At the end


1 Function introduction and quick start

The function is Organize code blocks with independent functions into a small module . When we develop programs, we can Improve writing efficiency and code reuse rate .

In this case, you may not realize the benefits of functions , Let's have a practical experience , The following code block is used to print the multiplication table , When the program is running , Will print a multiplication table :

for i in range(1, 10):
for j in range(1, i+1):
print(j, " * ", i, " = ", i*j, end="\t")
print()

If you need to print the multiplication formula table 100 And then ? Do you need to write the above code block 100 Time? ? The answer is No , When we learn about functions , Just define a function as follows , Encapsulate the code block of the function of printing multiplication formula table into the function :

def myprint():
for i in range(1, 10):
for j in range(1, i+1):
print(j, " * ", i, " = ", i*j, end="\t")
print()

When you need to print the multiplication table , Just call the defined myprint() Function , The following code will print the multiplication formula table 6 Time !!!

myprint()
myprint()
myprint()
myprint()
myprint()
myprint()

What about? ? Isn't it very concise ! Now let's start to learn about functions systematically ~


2 Function USES

2.1 Function definition and description

The basic format of a function declaration is as follows :

def Function name ( parameter list ):
Encapsulated code
Return value
...

explain :

  • def It's English define Abbreviation ;
  • The function name should express the function of the function encapsulation code , Increase the readability of the program , It is also convenient for future use ;
  • The parameter list and return value are added selectively according to the needs of the program ;
  • Function name needs Conform to naming rules for identifiers .

Naming rules for identifiers :( review )

  • Sure By letter 、 Underline and numbers make up ;
  • Cannot start with a number , And cannot have the same name as the keyword .

2.2 Documentation notes for functions

In actual development , If you want to annotate a function , Should be in Defined function below , Use Three consecutive pairs of quotes Add document comments :

  1. stay Between the quotation marks Add descriptive text for the function ;

  2. stay The location of the function call , Using shortcut keys CTRL + Q You can view the description of the function ;

  3. Above the function definition , You should leave two blank lines with other code and comments .

2.3 The parameters of the function

Functional Parameters are filled in the parentheses after the function name , Multiple parameters are shown in , Separate .
A simple demonstration of the function of finding the sum of two numbers , There are two arguments in this function , Calling this function will print the result of the sum of two numbers , The parameters passed in each call are different , The printed results are different , Make functions more flexible

def sum(num1, num2):
result = num1 + num2
print("%d + %d = %d" % (num1, num2, result))
sum(1, 3)
sum(99, 1)

Discriminating the formal parameters of real participation

  • Shape parameter : When defining a function , Parameters in parentheses , Is used to receive parameters , Used as a variable inside a function , Such as the above sum Function num1 And num2;
  • Actual parameters : When you call a function , Parameters in parentheses , It is used to transfer data to the function for internal use , For example, in the above sum Function 1 and 3,99 and 1.

2.4 The return value of the function

In program development , If you want to Function returns a result after execution , For subsequent processing by the caller , You need to give the function a return value .

  • Use... In functions return Keywords return results ;
  • The party calling the function , You can use variables to receive the return value of a function ;
  • return Said to return to , When the statement executes , Then subsequent code will not execute .

We design a return value for the previous summation function , send sum Returns the sum of two numbers , Filter out and greater than on external calls 5 The situation of

def sum(num1, num2):
return num1 + num2
for i in range(1, 6):
for j in range(i, 6):
result = sum(i, j)
if result > 5:
print(i, " + ", j, " = ", result)

2.5 Nested calls to functions

namely Calling another function in one function , Let's look at the following code :

def method01():
print("method01")
method02()
print("method01")
def method02():
print("---method02---")
method01()

explain :

  • When calling method01 when , Execute first method01 Statement in method body , When executed to the call method02() In this sentence , Then execute first method02() Execute all statements in the method01() Method .

3 Function specific training

3.1 Fibonacci sequence

Fibonacci sequence (Fibonacci sequence), Also called golden section series , Leonardo the mathematician · Fibonacci (Leonardo Fibonacci) Take rabbit breeding as an example , It is also called “ Rabbit Series ”, It refers to such a sequence :1、1、2、3、5、8、13、21、34、…… In Mathematics , The Fibonacci sequence is defined recursively as follows :F(0)=0,F(1)=1, F(n)=F(n - 1)+F(n - 2)(n ≥ 2,n ∈ N*)

problem : Please write a function Fabonacci(n), The parameter n On behalf of the n Times of iteration , To realize the quest for Fibonacci n Function of item value .

1️⃣ Mode one : Use recursive
Tips: If you are not familiar with recursion , You can refer to this blog post :
️ Understand recursion in simple terms ️

# Returns the... Of the Fibonacci sequence n term 
def fabonacci(n):
if n == 1 or n == 2:
return 1
else:
return fabonacci(n-1) + fabonacci(n-2)

2️⃣ Mode two : Use loop

# Returns the... Of the Fibonacci sequence n term 
def fabonacci(n):
if n == 1 or n == 2:
return 1
else:
num1 = 1 # The first one is 
num2 = 1 # The second item 
result = 0 # Records of the results 
while n > 2:
result = num1 + num2
num1 = num2
num2 = result
n = n - 1
return result

The test code is as follows , Used to print the first... Of Fibonacci series 10 term :

# Try printing Fibonacci before 10 term 
for i in range(1, 11):
print(fabonacci(i), end=" ")

3.2 Prime judgment

Prime number ( prime number ) Is greater than 1 Of the natural number , except 1 And a natural number that has no more factors than itself .

problem : Write a function Prime(n), For a known positive integer n, Judge whether the number is prime , If it's a prime number , return True, Otherwise return to False.

analysis : We just need to judge whether a number can be divided in a loop 1 And all other numbers except the body

Reference code :

# Judge whether it is a prime , If so, return True
def prime(n):
if n < 2:
return False
i = 2
while i <= n**0.5:
if n % i == 0:
return False
i = i + 1
return True

3.3 Twin prime number

problem : Use the function of judging prime numbers in the above question , Write a program to find out 1~100 Between all twin primes ( If the difference between two prime numbers is 2, be These two primes are twin primes ) . for example : 3 and 5、5 and 7、11 and 13 And so on are twin primes .

Reference code :

# Judge whether it is a prime , If so, return True
def prime(n):
if n < 2:
return False
i = 2
while i <= n**0.5:
if n % i == 0:
return False
i = i + 1
return True
# Test printing 1-100 The twin prime of 
# Using enumeration 
for i in range(1, 101):
if prime(i) and prime(i + 2):
print(str(i) + " And " + str(i+2), end=" ")

Running results :

3.4 Temperature conversion

problem : Write a function , Convert Celsius to Fahrenheit .( The formula : C*1.8+32=F)

analysis : This question involves the problem of mutual transformation , That is, one function implements two functions , Consider setting two parameters , One is used to judge whether Celsius to Fahrenheit or Fahrenheit to Celsius , One is used to pass in the temperature value

Reference code :

# Degrees Fahrenheit and centigrade change C*1.8+32=F
def calculate(typeNum, inputnum):
# typeNum by 1 Is Celsius to Fahrenheit 
if typeNum == 1:
result = inputnum * 1.8 + 32
print(inputnum, "℃ = ", result, "F")
# typeNum by 1 Is Celsius to Fahrenheit 
elif typeNum == 2:
result = (inputnum - 32) / 1.8
print(inputnum, "F = ", result, "℃")
else:
print(" Incorrect input ")
# test 
typenum = int(input(" Please select the type of input , Centigrade / Fahrenheit (1/2): "))
inputnum = float(input(" Please input the temperature value : "))
calculate(typenum, inputnum)

Running results :


3.5 Bean pile problem

problem : There are... In the pile 16 A bean , There are two players ( Suppose a player is a computer ) Every player can get from the pile 16 Take out a bean 1 star , 2 Or 3 A bean . Each player must take a certain number of beans from the pile in each turn . Players take turns taking out beans , To the end A bean player is a loser . Please write a program , Simulated bean pile game .

Ideas : Write a function for a person to take beans ; Help the computer design an algorithm , Implement the function of taking beans ; Make a stream transfer call in the main program , Who finally got 1 A bean loses .

Reference code :

import random
# The player 
def people(n):
print("-------------------------------------------")
while True:
pick_people = int(input(" How many beans are you going to take : "))
if 1 <= pick_people <= 3:
break
else:
print(" The number of beans taken out each time should be 1——3, Please re-enter !")
continue
print(" The number of beans remaining :", n - pick_people)
return n - pick_people
# The computer 
def computer(n):
pick_computer = random.randint(1, 3)
print(" Computer players take out beans and count :", pick_computer)
print(" The number of beans remaining :", n - pick_computer)
return n - pick_computer
def play():
total = 16
print(" The total number of beans is :", total)
while True:
total = people(total)
if total <= 0:
print(" I'm sorry , Did you lose ")
break
total = computer(total)
if total <= 0:
print(" congratulations , You win ")
break
# Start the game 
play()

Running results :


At the end

The above is the whole content of this article , The follow-up will continue Free update , If the article helps you , Please use your hands Point a praise + Focus on , Thank you very much ️ ️ ️ !
If there are questions , Welcome to the private letter or comment area !

Mutual encouragement :“ You make intermittent efforts and muddle through , It's all about clearing the previous efforts .”


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved