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

Python -- functions

編輯:Python
def print_area(length):
area=length*length
return(area)
result=print_area(12)
print(f" The area of this square is {result}")

among f Indicates format output , Use curly braces to enclose the variable you want to replace , In order to realize this function .

def Represents the constructed function , Function is only called later , The system will execute the relevant code of the function , Otherwise, the system will directly skip the relevant code . Besides , Suppose you want to use the result of a function run , Use the return value , So that the result can be passed back to the place of the call .( The understanding here is similar to c++ Exactly the same, but in a slightly different form )

If return Inside the loop , Then the loop of this function will only execute once , From then to return when , The loop will automatically end . Stop this function call .

And c++ The difference is ,python Multiple values can be returned at the same time , for instance ( Don't leave out the colon )

def print_area(length):
area=length*length
return area,length
result=print_area(12)
print(f" The area of this square is {result}")

When multiple values are returned , Need to use “,” separation , So the compiler will Returns the relevant data in the form of tuples

If there is no return value in the function , Then a null value will be returned (NULL)

Add a few simple functions

print() Output some data range() Generate a list of numbers listappend() Append an element to the list len() Returns the length of the tuple of the character list or the number of elements

python The default value of the parameter in the function

def print_area(length=100):
area=length*length
return area,length
result=print_area()
print(f" The area of this square is {result}")

Be careful : If when calling a function , Is not a parameter length Provide parameters , So parameters length The default is 100.

The default parameter can have any number of , But it must be defined after the required parameter , If the required parameter exists .

Define the order of function parameters :

1、 Required parameters

2、 Default parameters

When there are required parameters and default parameters , The required parameter must be written before the default parameter , Otherwise, the program will report an error .


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