Hướng dẫn keyword parameter in python
Besides the Nội dung chính Nội dung chính 4.1. if Statements¶Perhaps the most well-known statement type is the >>> x=int(input("Please enter an integer: "))Please enter an integer: 42>>> ifx<0:... x=0... print('Negative changed to zero')... elifx==0:... print('Zero')... elifx==1:... print('Single')... else:... print('More')...More There can be zero or more If you’re comparing
the same value to several constants, or checking for specific types or attributes, you may also find the 4.2. for Statements¶The >>> # Measure some strings:... words=['cat','window','defenestrate']>>> forwinwords:... print(w,len(w))...cat 3window 6defenestrate 12 Code that modifies a collection while iterating over that same collection can be tricky to get right. # Create a sample collectionusers={'Hans':'active','Éléonore':'inactive','景太郎':'active'}# Strategy: Iterate over a copyforuser,statusinusers.copy().items():ifstatus=='inactive':delusers[user]# Strategy: Create a new collectionactive_users={}foruser,statusinusers.items():ifstatus=='active':active_users[user]=status 4.3. The range() Function¶If you do need to iterate over a sequence of numbers, the built-in function >>> foriinrange(5):... print(i)...01234 The given end point is never part of the generated sequence; >>> list(range(5,10))[5, 6, 7, 8, 9]>>> list(range(0,10,3))[0, 3, 6, 9]>>> list(range(-10,-100,-30))[-10, -40, -70] To iterate over the indices of a sequence, you can combine >>> a=['Mary','had','a','little','lamb']>>> foriinrange(len(a)):... print(i,a[i])...0 Mary1 had2 a3 little4 lamb In most such cases, however, it is convenient to use the A strange thing happens if you just print a range: >>> range(10)range(0, 10) In many ways the object We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the >>> sum(range(4))# 0 + 1 + 2 + 36 Later we will see more functions that return iterables and take iterables as arguments. In chapter Data Structures, we will discuss in more detail about 4.4. break and continue Statements, and else Clauses on Loops¶The Loop statements may have an >>> forninrange(2,10):... forxinrange(2,n):... ifn%x==0:... print(n,'equals',x,'*',n//x)... break... else:... # loop fell through without finding a factor... print(n,'is a prime number')...2 is a prime number3 is a prime number4 equals 2 * 25 is a prime number6 equals 2 * 37 is a prime number8 equals 2 * 49 equals 3 * 3 (Yes, this is the correct code. Look closely: the When used with a loop, the The >>> fornuminrange(2,10):... ifnum%2==0:... print("Found an even number",num)... continue... print("Found an odd number",num)...Found an even number 2Found an odd number 3Found an even number 4Found an odd number 5Found an even number 6Found an odd number 7Found an even number 8Found an odd number 9 4.5. pass Statements¶The >>> whileTrue:... pass# Busy-wait for keyboard interrupt (Ctrl+C)... This is commonly used for creating minimal classes: >>> classMyEmptyClass:... pass... Another place >>> definitlog(*args):... pass# Remember to implement this!... 4.6. match Statements¶A The simplest form compares a subject value against one or more literals: defhttp_error(status):matchstatus:case400:return"Bad request"case404:return"Not found"case418:return"I'm a teapot"case_:return"Something's wrong with the internet" Note the last block: the “variable name” You can combine several literals in a single pattern using case401|403|404:return"Not allowed" Patterns can look like unpacking assignments, # point is an (x, y) tuplematchpoint:case(0,0):print("Origin")case(0,y):print(f"Y={y}")case(x,0):print(f"X={x}")case(x,y):print(f"X={x}, Y={y}")case_:raiseValueError("Not a point") Study that one carefully! The first pattern has two literals, and can be thought of as an extension of the literal pattern shown above. But the next two patterns combine a literal and a variable, and the variable binds a value from the subject ( If you are using classes to structure your data you can use the class name classPoint:x:inty:intdefwhere_is(point):matchpoint:casePoint(x=0,y=0):print("Origin")casePoint(x=0,y=y):print(f"Y={y}")casePoint(x=x,y=0):print(f"X={x}")casePoint():print("Somewhere else")case_:print("Not a point") You can use positional parameters with some builtin classes that provide an ordering for their attributes (e.g. dataclasses). You can also define a specific position for attributes in patterns by setting the Point(1,var)Point(1,y=var)Point(x=1,y=var)Point(y=var,x=1) A recommended way to read patterns is to look at them as an extended form of what you would put on the left of an assignment, to understand which variables would be set to what. Only the standalone names (like Patterns can be arbitrarily matchpoints:case[]:print("No points")case[Point(0,0)]:print("The origin")case[Point(x,y)]:print(f"Single point {x}, {y}")case[Point(0,y1),Point(0,y2)]:print(f"Two on the Y axis at {y1}, {y2}")case_:print("Something else") We can add an matchpoint:casePoint(x,y)ifx==y:print(f"Y=X at {x}")casePoint(x,y):print(f"Not on the diagonal") Several other key features of this statement:
For a more detailed explanation and additional examples, you can look into PEP 636 which is written in a tutorial format. 4.7. Defining Functions¶We can create a function that writes the Fibonacci series to an arbitrary boundary: >>> deffib(n):# write Fibonacci series up to n... """Print a Fibonacci series up to n."""... a,b=0,1... whilea<n:... print(a,end=' ')... a,b=b,a+b... print()...>>> # Now call the function we just defined:... fib(2000)0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 The keyword The first statement of the function body can optionally be a string literal; this string literal is the function’s
documentation string, or docstring. (More about docstrings can be found in the section Documentation Strings.) There are tools which use docstrings to automatically produce online or printed documentation, The execution of a function introduces a new symbol table used for the local variables of the function. More precisely, all
variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol The actual parameters (arguments) to a function call are introduced in the local symbol table of the called function when it is called; thus, arguments are A function definition associates the
function name with the function object in the current symbol table. The interpreter recognizes the object pointed to by that name as a user-defined function. Other names can also point to that same function object and can also be >>> fib Coming from other languages, you might object that >>> fib(0)>>> print(fib(0))None It >>> deffib2(n):# return Fibonacci series up to n... """Return a list containing the Fibonacci series up to n."""... result=[]... a,b=0,1... whilea<n:... result.append(a)# see below... a,b=b,a+b... returnresult...>>> f100=fib2(100)# call it>>> f100# write the result[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] This example, as usual, demonstrates some new Python features:
4.8. More on Defining Functions¶It is also possible to define functions with a variable number of arguments. There are three forms, which can be combined. 4.8.1. Default Argument Values¶The most useful form is to specify a default value for one or more defask_ok(prompt,retries=4,reminder='Please try again!'):whileTrue:ok=input(prompt)ifokin('y','ye','yes'):returnTrueifokin('n','no','nop','nope'):returnFalseretries=retries-1ifretries<0:raiseValueError('invalid user response')print(reminder) This function can be called in several ways:
This example also introduces the The default i=5deff(arg=i):print(arg)i=6f() will print Important warning: The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. For example, the following function accumulates the arguments passed to it on subsequent calls: deff(a,L=[]):L.append(a)returnLprint(f(1))print(f(2))print(f(3)) This will print If you don’t want the default to be shared deff(a,L=None):ifLisNone:L=[]L.append(a)returnL 4.8.2. Keyword Arguments¶Functions can also be called using keyword arguments of the form defparrot(voltage,state='a stiff',action='voom',type='Norwegian Blue'):print("-- This parrot wouldn't",action,end=' ')print("if you put",voltage,"volts through it.")print("-- Lovely plumage, the",type)print("-- It's",state,"!") accepts one required argument ( parrot(1000)# 1 positional argumentparrot(voltage=1000)# 1 keyword argumentparrot(voltage=1000000,action='VOOOOOM')# 2 keyword argumentsparrot(action='VOOOOOM',voltage=1000000)# 2 keyword argumentsparrot('a million','bereft of life','jump')# 3 positional argumentsparrot('a thousand',state='pushing up the daisies')# 1 positional, 1 keyword but parrot()# required argument missingparrot(voltage=5.0,'dead')# non-keyword argument after a keyword argumentparrot(110,voltage=220)# duplicate value for the same argumentparrot(actor='John Cleese')# unknown keyword argument In a function call, keyword
arguments must follow positional arguments. All the keyword arguments passed must match one of the arguments accepted by the function (e.g. >>> deffunction(a):... pass...>>> function(0,a=0)Traceback (most recent call last): File " When a final formal parameter of the form defcheeseshop(kind,*arguments,**keywords):print("-- Do you have any",kind,"?")print("-- I'm sorry, we're all out of",kind)forarginarguments:print(arg)print("-"*40)forkwinkeywords:print(kw,":",keywords[kw]) It could be called like this: cheeseshop("Limburger","It's very runny, sir.","It's really very, VERY runny, sir.",shopkeeper="Michael Palin",client="John Cleese",sketch="Cheese Shop Sketch") and of course it would print: -- Do you have any Limburger ? -- I'm sorry, we're all out of Limburger It's very runny, sir. It's really very, VERY runny, sir. ---------------------------------------- shopkeeper : Michael Palin client : John Cleese sketch : Cheese Shop Sketch Note that the order in which the keyword arguments are printed is guaranteed to match the order in which they were provided in the function call. 4.8.3. Special parameters¶By default, arguments may be passed to a Python function either by position or explicitly by keyword. For readability and performance, it makes sense to A function definition may look like: def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): ----------- ---------- ---------- | | | | Positional or keyword | | - Keyword only -- Positional only where 4.8.3.1. Positional-or-Keyword Arguments¶If 4.8.3.2. Positional-Only Parameters¶Looking at this in a bit more detail, it is
possible to mark certain parameters as positional-only. If positional-only, the parameters’ order matters, and the parameters cannot be passed by Parameters following the 4.8.3.3. Keyword-Only Arguments¶To mark parameters as keyword-only, indicating the 4.8.3.4. Function Examples¶Consider the
following example function definitions paying close attention to the markers >>> defstandard_arg(arg):... print(arg)...>>> defpos_only_arg(arg,/):... print(arg)...>>> defkwd_only_arg(*,arg):... print(arg)...>>> defcombined_example(pos_only,/,standard,*,kwd_only):... print(pos_only,standard,kwd_only) The first function definition, >>> standard_arg(2)2>>> standard_arg(arg=2)2 The second function >>> pos_only_arg(1)1>>> pos_only_arg(arg=1)Traceback (most recent call last): File " The third function >>> kwd_only_arg(3)Traceback (most recent call last): File " And the last uses all three calling conventions in the same function definition: >>> combined_example(1,2,3)Traceback (most recent call last): File " Finally, consider this function definition which has a potential collision between the positional argument deffoo(name,**kwds):return'name'inkwds There is no possible call that will make it return >>> foo(1,**{'name':2})Traceback (most recent call last): File " But using
deffoo(name,/,**kwds):return'name'inkwds>>>foo(1,**{'name':2})True In other words, the names of positional-only parameters can be used in 4.8.3.5. |