Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Tham khảo tài liệu 'programming in python 3 - part 4', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 174 Chapter 4. Control Structures and Functions def letter_count text letters string.ascii_letters letters frozenset letters count 0 for char in text if char in letters count 1 return count We have specified a default value for the letters parameter by using the parameter default syntax. This allows us to call letter_count with just one argument for example letter_count Maggie and Hopey . Here inside the function letters will be the string that was given as the default value. But we can still change the default for example using an extra positional argument letter_count Maggie and Hopey aeiouAEIOU or using a keyword argument coverednext letter_count Maggie and Hopey letters aeiouAEIOU . The parameter syntax does not permit us to follow parameters with default values with parameters that don t have defaults so def bad a b 1 c won t work. On the other hand we are not forced to pass our arguments in the order they appear in the function s definition instead we can use keyword arguments passing each argument in the form name value. Here is a tiny function that returns the string it is given or if it is longer than the specified length it returns a shortened version with an indicator added def shorten text length 25 indicator . if len text length text text length - len indicator indicator return text Here are a few example calls shorten The Silkie returns The Silkie shorten length 7 text The Silkie returns The . shorten The Silkie indicator length 7 returns The Si shorten The Silkie 7 returns The Si Because both length and indicator have default values either or both can be omitted entirely in which case the default is used this is what happens in the first call. In the second call we use keyword arguments for both of the specified parameters so we can order them as we like. The third call mixes both positional and keyword arguments. We used a positional first argument positional arguments must always precede keyword arguments and then two keyword arguments. The fourth