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

Python3 functions -python introduction to mastery

編輯:Python

Preface

More , Please visit mine Personal blog .


function

A function is a reusable 、 A block of code that implements a specific function .
The feature of the function is that it can improve the application Modularity , And code reusability .

grammar

Python Define function use def keyword , The general format is as follows :

def Function name ( parameter list ):
The body of the function

We need to pay attention to the following :

  • Function code block to def Key words start with , Followed by function identifier name and parentheses ().
  • Any arguments and arguments passed in must be placed between parentheses , Parentheses can be used to define parameters .
  • The first line of the function optionally uses the document string , Used to store function descriptions .
  • Function contents start with a colon , And indent .
  • return [ expression ] End function , Optionally return a value to the caller . Without expression return It's equivalent to returning to None .

for instance

Let's write a function , For output Hello Python! .

def hello():
print("Hello Python!")

Add a comment to the function .

def hello():
""" Output Hello """
print("Hello Python!")

Add a parameter , And set default values for parameters .

def hello(name='Python'):
""" Output Hello """
print("Hello " + name + "!")

Set return value , If we do not set up , The default return value is None .

def hello(name='Python'):
""" Output Hello """
print("Hello " + name + "!")
return 'ok'

Call function .

def hello(name='Python'):
""" Output Hello """
print("Hello " + name + "!")
return 'ok'
h = hello()
print(h)

Exercises

Find out the errors and irregularities in the following code .

def getMax(a=0, b = 0, c)
''' return a,b,c The largest of the three numbers '''
if a >= b and a > c:
return a;
elseif b > a && b > c:
return b
else:
return c
return None

Official account : Pangao will accompany you to learn programming , reply 018, Get the answer to the exercise .



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