search
HomeBackend DevelopmentPython TutorialA brief discussion on parameter passing of functions in Python

1. Ordinary parameter passing

>>> def add(a,b): 
  return a+b 
 
>>> print add(1,2) 
3
>>> print add('abc','123') 
abc123

2. The number of parameters is optional, and the parameters are passed with default values ​​

>>> def myjoin(string,sep='_'): 
  return sep.join(string) 
 
>>> myjoin('Test') 
'T_e_s_t'
>>> myjoin('Test',';') 
'T;e;s;t' 
?
>>> def myrange(start=0,stop,step=1): 
  print stop,start,step 
   
SyntaxError: non-default argument follows default argument

The default value of parameter sep is '_' If this parameter is not given a value, the default value will be used. If it is given, the given value will be used

It should be noted that if a parameter is an optional parameter, then all the parameters following it should be optional. In addition, If the order of the optional parameters is reversed, the corresponding parameters can still be correctly assigned, but the variable name and value must be clearly specified

3. Number of variable parameters

>>> def printf(fmt,*arg): 
  print fmt%arg 
 
   
>>> printf ('%d is larger than %d',2,1) 
2 is larger than 1

The *arg in the function must be the last parameter, * means any number of parameters, *arg will put all the parameters except the previous ones into one The tuple is passed to the function and can be accessed through arg in the function

arg is a tuple, and arg can be accessed in the function through the method of accessing tuple

Another way to pass any number Parameters are passed through dictionary and can also accept multiple parameters, but each parameter needs to specify the name correspondence, such as a=1, b=2, c=3

>>> def printf(format,**keyword): 
  for k in keyword.keys(): 
    print "keyword[%s] %s %s"%(k,format,keyword[k]) 
 
     
>>> printf('is',one=1,tow=2,three=3) 
keyword[three] is 3
keyword[tow] is 2
keyword[one] is 1

These methods can be mixed together but the order must be paid attention to. The function will first accept fixed parameters, then optional parameters, then arbitrary parameters (tuple), then dictionary arbitrary parameters (dict)

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools