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 Có thể bạn quan tâmclassPoint: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. |
Bài Viết Liên Quan
Hướng dẫn dùng open in python
Nội dung chínhCách 1: Sử dụng hàm openCách 2: mở file sử dụng context managerCách 3: Sử dụng thư viện pathlibCách 4: Sử dụng shellCách 5: Xây dựng một thư viện ...
Mùng 6 tết 2023 là ngày mấy
Chẳng bao lâu nữa thì mùa xuân năm 2023 lại về với những khởi đầu mới và hứng khởi mới. Chắc hẳn là hiện tại cũng đang có rất nhiều bạn mong muốn ...
Hướng dẫn convert json string to list of dictionaries python - chuyển đổi chuỗi json thành danh sách từ điển python
19 Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.Learn more. Tôi đang gửi một chuỗi JSON từ Objective-C đến Python. ...
Hướng dẫn python is an interpreted high-level language what does it mean to you - python là một ngôn ngữ cấp cao được thông dịch, nó có ý nghĩa như thế nào đối với bạn
Python là một trong những ngôn ngữ được giải thích phổ biến nhất, nhưng bạn đã bao giờ nghĩ về lý do tại sao Python được gọi là ngôn ngữ được giải ...
Hướng dẫn uniroot python - trăn uniroot
Hướng dẫn fuzzy python - trăn mờChuỗi mờ khớp trong PythonChúng tôi đã thực hiện nhiệm vụ của mình để lấy vé sự kiện từ mọi góc của internet, cho bạn ...
Hướng dẫn how do you sum two inputs in python? - làm thế nào để bạn tổng hợp hai đầu vào trong python?
Trong chương trình này, bạn sẽ học cách thêm hai số và hiển thị nó bằng hàm in ().Để hiểu ví dụ này, bạn nên có kiến thức về các chủ đề lập ...
Hướng dẫn sensitivity analysis python code - phân tích độ nhạy mã python
Composite number in python assignment expertComposite NumberGiven an integer N, write a program to find if the given number is a composite number or not. If it is composite, print True or else print ...
Hướng dẫn is there lcm function in python? - có chức năng lcm trong python không?
Trong chương trình này, bạn sẽ học cách tìm LCM của hai số và hiển thị nó.Để hiểu ví dụ này, bạn nên có kiến thức về các chủ đề lập trình ...
Hướng dẫn how do you click an element in python? - làm thế nào để bạn nhấp vào một phần tử trong python?
Xem thảo luậnCải thiện bài viếtLưu bài viếtĐọcBàn luậnXem thảo luậnCải thiện bài viếtLưu bài viếtĐọcBàn luậnMô -đun Selenium sườn Python được xây ...
Hướng dẫn is python more versatile than r? - python có linh hoạt hơn r không?
Khám phá những điều cơ bản của hai ngôn ngữ lập trình nguồn mở này, sự khác biệt chính làm cho chúng khác biệt và cách chọn đúng ngôn ngữ cho tình huống ...
Hướng dẫn is python little or big endian? - trăn nhỏ hay endian lớn?
21 Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.Learn more. Tôi đang làm việc trên một chương trình nơi tôi lưu ...
Hướng dẫn python get thread id - python lấy id chuỗi
246 Mới! Lưu câu hỏi hoặc câu trả lời và sắp xếp nội dung yêu thích của bạn. Tìm hiểu thêm.Learn more. Tôi có một chương trình Python đa luồng và chức năng ...
Hướng dẫn eclipse javascript - javascript nhật thực
Chào các bạn, trong bài viết này mình sẽ hướng dẫn mọi người tìm hiểu về một IDE (Integrated Development Environment) cực kỳ phổ biến đối với những lập ...
Lệnh thay đổi password trong linux
Trong bài này mình sẽ hướng dẫn cách đổi mật khẩu người dùng trên Linux, bằng cách sử dụng lệnh passwd Linux là bạn có thể đổi mật khẩu user trên Linux ...
25 tháng chạp 2023
Mục lục1 Lịch vạn niên ngày 25 tháng 12 năm 20232 Tử vi tốt xấu ngày 25 tháng 12 năm 20232.1 ☯ Việc tốt trong ngày2.2 ☯ Ngày bách kỵ2.3 ❎ Danh sách giờ xấu ...
Hướng dẫn how do i download mysql jdbc connector? - làm cách nào để tải xuống trình kết nối jdbc mysql?
Tải xuống cộng đồng MySQL Đầu nối/j Tính khả dụng chung (GA) phát hànhLưu trữĐầu nối/j 8.0.31 Chọn hệ điều hành: Tải xuống Windows được đề ...
Hướng dẫn ssh python - trăn ssh
Tiếp series lập trình Python, xin giới thiệu với các bạn đoạn code Python 3 sau sử dụng thư viện paramiko có nhiệm vụ kết nối SSH tới 1 Remote Linux Server và ...
Hướng dẫn how does php know the session? - làm thế nào để php biết phiên?
Một phiên là một cách để lưu trữ thông tin (trong các biến) sẽ được sử dụng trên nhiều trang.Không giống như cookie, thông tin không được lưu trữ trên máy ...
Hướng dẫn trinket python compiler - trình biên dịch trăn trinket
Hướng dẫn how do you extract something from a list in python? - làm thế nào để bạn trích xuất một cái gì đó từ một danh sách trong python?Hãy cùng tìm hiểu các cách ...
Lấy dữ liệu từ web vào excel trên macbook
Lấy dữ liệu, báo cáo từ website nhanh chóng với Excel là thủ thuật ít người biết đến. Trong bài viết dưới đây, chúng ta hãy cùng khám phá tính năng lấy ...