We know that if a parameter is not specified when calling a function, the Python interpreter will throw an exception. In order to solve this problem, Python allows setting default values for parameters, that is, when defining a function, directly specify a default value for the formal parameters. In this case, even if no parameter is passed to a formal parameter with a default value when the function is called, the parameter can directly use the default value set when the function is defined.
Python defines a function with default value parameters. The syntax format is as follows:
def 函数名(...,形参名,形参名=默认值): 代码块
Note that when using this format to define a function, the formal parameters with default values must be specified in all default values. value parameter at the end, otherwise a syntax error will occur.
The following program demonstrates how to define and call a function with default parameters:
#str1没有默认参数,str2有默认参数 def dis_str(str1,str2 = "http://c.biancheng.net/python/"): print("str1:",str1) print("str2:",str2) dis_str("http://c.biancheng.net/shell/") dis_str("http://c.biancheng.net/java/","http://c.biancheng.net/golang/")
The running result is:
str1: http://c.biancheng. net/shell/
str2: http://c.biancheng.net/python/
str1: http://c.biancheng.net/java/
str2: http://c.biancheng .net/golang/
In the above program, the dis_str() function has 2 parameters, the second of which has a default parameter. This means that when calling the dis_str() function, we can pass in only 1 parameter, which will be passed to the str1 parameter, and str2 will use the default parameters, as shown in line 6 of the program.
Of course, when calling the dis_str() function, you can also pass values to all parameters (as shown in line 7 of the code). At this time, even if str2 has a default value, it will give priority to the parameters passed to it. new value.
At the same time, combined with keyword parameters, the following three ways of calling the dis_str() function are also possible:
dis_str(str1 = "http://c.biancheng.net/shell/") dis_str("http://c.biancheng.net/java/",str2 = "http://c.biancheng.net/golang/") dis_str(str1 = "http://c.biancheng.net/java/",str2 = "http://c.biancheng.net/golang/")
Again, when defining a function with default value parameters, there are parameters with default values. Must come after all parameters without default values. Therefore, the function defined in the following example is incorrect:
#语法错误 def dis_str(str1="http://c.biancheng.net/python/",str2,str3): pass
Obviously, str1 has a default value, while str2 and str3 do not have default values, so str1 must be located after str2 and str3.
Some readers may ask, for your own custom functions, you can easily know which parameters have default values, but if you use the built-in functions provided by Python, or functions provided by other third parties, how do you know which parameters? Is there a default value?
In Pyhton, you can use "function name.__defaults__" to view the current value of the function's default value parameter, and its return value is a tuple. Take the dis_str() function in this section as an example. Based on it, execute the following code:
print(dis_str.__defaults__)
The program execution result is:
('http://c. biancheng.net/python/',)
The above is the detailed content of How to set the default parameters of Python functions. For more information, please follow other related articles on the PHP Chinese website!

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i

Forloopsareadvantageousforknowniterationsandsequences,offeringsimplicityandreadability;whileloopsareidealfordynamicconditionsandunknowniterations,providingcontrolovertermination.1)Forloopsareperfectforiteratingoverlists,tuples,orstrings,directlyacces

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

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

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor
