Day03 -- Python function, day03python

Source: Internet
Author: User

Day03 -- Python function, day03python

Function Definition and use

1. Syntax

Def function name (parameter):... function body... return value

Functions are defined as follows:

Def: indicates the function keyword.
Function Name: name of the function. The function will be called Based on the function name in the future.
Function body: perform a series of logical calculations in the function, such as sending emails and calculating the maximum number in [11, 22, 38,888, 2...
Parameter: provides data for the function body.
Return Value: After the function is executed, the caller can return data.

2. Return Value

After the function is executed, the execution result is returned, for example:

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef test():    """        test codes ...    """    if 1 == 1:        return True    else:        return Falsestatus=test()print(status)

3. Parameters

Python function parameters include common parameters, default parameters, and dynamic parameters.

(1) Common Parameters

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef fname(name):    print('My name is :%s'%name)fname('Lucy')

(2) default parameters

#!/usr/bin/env python# -*- UTF-8 -*-# Author:Rangledef fname(name,age=18):    print('My name is :%s and i\'am %s years old'%(name,age))fname('Lucy')

(3) Dynamic Parameters

# Receive dynamic parameters. The dynamic parameters include strings, numbers, and list formats. The output format is tuples.

#! /Usr/bin/env python #-*-UTF-8-*-# Author: Rangledef func (* args): print (args) # execution method 1 func (11,33, 4,4454, 5) # execution method 2 li = [11, 2, 3, 3, 4, 54] func (* li)

# Receive dynamic parameters. The parameters are in dictionary format and the output format is dictionary.

#! /Usr/bin/env python #-*-UTF-8-*-# Author: Rangledef func (** kwargs): print (kwargs) # execution method 1 func (name = 'Lucy ', age = 18) # execution method 2 li = {'name': 'Lucy', 'age': 18, 'Gender': 'male'} func (** li)

# Receive dynamic parameters in combination

def func(*args, **kwargs):    print args    print kwargs

4. built-in functions

Official Website: https://docs.python.org/3/library/functions.html#next

(1) open () function

For file processing, the steps are generally: open a file --> operate a file --> close a file

Syntax:

File handle = open ('file path', 'Mode ')

File opening modes include:

  • R, read-only mode [Default]
  • W, write-only mode: [unreadable; created if no data exists; cleared if data exists ;]
  • X, write-only mode [unreadable; created if no data exists; an error is returned if data exists]
  • A. The append mode is readable. If it does not exist, the append mode is created. If it exists, only the content is appended ;]

"+" Indicates that a file can be read and written simultaneously.

  • R +, read/write [readable, writable]
  • W +, write and read [readable, writable]
  • X +, write and read [readable, writable]
  • A +, write and read [readable, writable]

"B" indicates byte operations

  • Rb or r + B
  • Wb or w + B
  • Xb or w + B
  • AB or a + B

Note: When opened in the B mode, the read content is of the byte type, and the bytes type also needs to be provided during writing.

 

Class file (object) def close (self): # real signature unknown; restored from _ doc _ close file "close ()-> None or (perhaps) an integer. close the file. sets data attribute. closed to True. A closed file cannot be used for further I/O operations. close () may be called more than once without error. some kinds of file objects (for example, opened by popen () may return an exit status upon closing. "def fileno (self): # real signature unknown; restored from _ doc _ file descriptor" fileno ()-> integer "file descriptor ". this is needed for lower-level file interfaces, such OS. read (). "" return 0 def flush (self): # real signature unknown; restored from _ doc _ refresh File Buffer "flush ()-> None. flush the internal I/O buffer. "pass def isatty (self): # real signature unknown; restored from _ doc _ determine whether the file agrees to the tty device" isatty ()-> true or false. true if the file is connected to a tty device. "" return False def next (self): # real signature unknown; restored from _ doc _ get the next row of data. If the row does not exist, an error is returned. "" x. next ()-> the next value, or raise StopIteration "" pass def read (self, size = None): # real signature unknown; restored from _ doc _ read specified byte data "read ([size])-> read at most size bytes, returned as a string. if the size argument is negative or omitted, read until EOF is reached. notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. "pass def readinto (self): # real signature unknown; restored from _ doc _ read to the buffer zone. Do not use it. It will be abandoned" readinto () -> uninitialized ented. don't use this; it may go away. "" pass def readline (self, size = None): # real signature unknown; restored from _ doc _ read only one row of Data "readline ([size]) -> next line from the file, as a string. retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then ). return an empty string at EOF. "" pass def readlines (self, size = None): # real signature unknown; restored from _ doc _ read all data, and save the Value list "readlines ([size])-> list of strings, each a line from the file. call readline () repeatedly and return a list of the lines so read. the optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. "" return [] def seek (self, offset, whence = None): # real signature unknown; restored from _ doc _ specifies the pointer position in the file "seek (offset [, whence])-> None. move to new file position. argument offset is a byte count. optional argument whence ults to (offset from start of file, offset shocould be> = 0); other values are 1 (move relative to current position, positive or negative ), and 2 (move relative to end of file, usually negative, although implements platforms allow seeking beyond the end of a file ). if the file is opened in text mode, only offsets returned by tell () are legal. use of other offsets causes undefined behavior. note that not all file objects are seekable. "pass def tell (self): # real signature unknown; restored from _ doc _ get the current pointer position" tell ()-> current file position, an integer (may be a long integer ). "" pass def truncate (self, size = None): # real signature unknown; restored from _ doc _ truncate data, only retain the specified previous data "truncate ([size])-> None. truncate the file to at most size bytes. size defaults to the current file position, as returned by tell (). "pass def write (self, p_str): # real signature unknown; restored from _ doc _ write content" write (str)-> None. write string str to file. note that due to buffering, flush () or close () may be needed before the file on disk reflects the data written. "pass def writelines (self, sequence_of_strings): # real signature unknown; restored from _ doc _ write a string list to a file" writelines (sequence_of_strings) -> None. write the strings to the file. note that newlines are not added. the sequence can be any iterable object producing strings. this is equivalent to calling write () for each string. "pass def xreadlines (self): # real signature unknown; restored from _ doc _ can be used to read files row by row, not all" xreadlines () -> returns self. for backward compatibility. file objects now include the performance optimizations previusly implemented in the xreadlines module. "pass2.x
2. x built-in functions

 

Class TextIOWrapper (_ TextIOBase): "" Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded. it defaults to locale. getpreferredencoding (False ). errors determines the strictness of encoding and decoding (see help (codecs. codec) or the documentation for codecs. register) and defaults to "strict ". newline controls how line endings are handled. it can be None, '', '\ n',' \ R', and '\ r \ n '. it works as follows: * On input, if newline is None, universal newlines mode is enabled. lines in the input can end in '\ n',' \ R', or '\ r \ n ', and these are translated into '\ n' before being returned to the caller. if it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. if it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\ n' characters written are translated to the system default line separator, OS. linesep. if newline is ''or '\ n', no translation takes place. if newline is any of the other legal values, any '\ n' characters written are translated to the given string. if line_buffering is True, a call to flush is implied when a call to write contains a newline character. "def close (self, * args, ** kwargs): # real signature unknown close the file pass def fileno (self, * args, ** kwargs ): # real signature unknown file descriptor pass def flush (self, * args, ** kwargs): # real signature unknown refresh file internal buffer pass def isatty (self, * args, ** kwargs): # real signature unknown checks whether the file agrees to the tty device pass def read (self, * args, ** kwargs ): # real signature unknown pass def readable (self, * args, ** kwargs): # Whether real signature unknown is readable pass def readline (self, * args, ** kwargs): # real signature unknown reads only one row of data pass def seek (self, * args, ** kwargs ): # real signature unknown specify the pointer position in the file pass def seekable (self, * args, ** kwargs): # whether the real signature unknown pointer can operate pass def tell (self, * args, ** kwargs): # real signature unknown get pointer position pass def truncate (self, * args, ** kwargs): # real signature unknown truncation data, retain only the specified data pass def writable (self, * args, ** kwargs): # Whether real signature unknown can write pass def write (self, * args, ** kwargs ): # pass def _ getstate _ (self, * args, ** kwargs): # real signature unknown pass def _ init _ (self, * args, ** kwargs): # real signature unknown pass @ staticmethod # known case of _ new _ def _ new _ (* args, ** kwargs ): # real signature unknown "Create and return a new object. see help (type) for accurate signature. "pass def _ next _ (self, * args, ** kwargs): # real signature unknown" Implement next (self ). "pass def _ repr _ (self, * args, ** kwargs): # real signature unknown" Return repr (self ). "pass buffer = property (lambda self: object (), lambda self, v: None, lambda self: None) # default closed = property (lambda self: object (), lambda self, v: None, lambda self: None) # default encoding = property (lambda self: object (), lambda self, v: None, lambda self: None) # default errors = property (lambda self: object (), lambda self, v: None, lambda self: None) # default line_buffering = property (lambda self: object (), lambda self, v: None, lambda self: None) # default name = property (lambda self: object (), lambda self, v: None, lambda self: None) # default newlines = property (lambda self: object (), lambda self, v: None, lambda self: None) # default _ CHUNK_SIZE = property (lambda self: object (), lambda self, v: None, lambda self: None) # default _ finalizing = property (lambda self: object (), lambda self, v: None, lambda self: None) # default3.x
3. x built-in functions

(2) management context of File Operations

Use the Open () function to hide and close the file. This may easily cause the file to be ignored and closed. You can use the with open () as f management context to automatically close a file. The syntax is as follows:

with open('log','r') as f:            ...

After 2.7, multiple files can be opened.

with open('log1') as obj1, open('log2') as obj2:    pass

(3) ternary operation

If 1 = 1 is true, name = 'Lucy 'is returned; otherwise, name = 'Tom' is returned'

name = 'Lucy' if 1 == 1 else 'Tom'

(4) Judgment Functions

S = 'abc'

 

S. isalnum () All characters are numbers or letters, True returns true, otherwise False returns. S. isalpha () All characters are letters, True returns true, Otherwise returns False. S. isdigit () All characters are numbers, True returns true, Otherwise returns False. S. islower () All characters are in lower case, True returns true, otherwise False returns. S. isupper () All characters are uppercase letters, True returns true, otherwise False returns. S. istitle () All words are uppercase letters, True returns true, otherwise False returns. S. isspace () All characters are blank characters. True returns true, otherwise False returns.

5. Exercise questions

(1) briefly describe the differences between common parameters, specified parameters, default parameters, and dynamic parameters (2), write functions, calculate the number of numbers, letters, spaces, and other values in the input string (3). Write a function to determine the input objects (string, list, And tuples) whether the length is greater than 5. (4) Write a function and check whether each element of the input object (string, list, And tuples) contains null content. (5) Write a function and check the length of the input list. If the length is greater than 2, only the content of the first two lengths is retained and the new content is returned to the caller. (6) Write a function to check and obtain all elements corresponding to the odd-digit index of the input list or tuples, and return the elements to the caller as a new list. (7) Write a function and check the length of each value in the input dictionary. If the value is greater than 2, only the content of the first two lengths is retained and the new content is returned to the caller. 123 dic = {"k1": "v1v1", "k2": [,]} PS: the value in the dictionary can only be a string or a list (8), write a function, recursively obtain the number of 10th in the Fibonacci series and return this value to the caller.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.