On-the-ground python "chapter III": Python Basics (iii)

Source: Internet
Author: User
Tags new set readline shallow copy

Python Basics (iii)Chapter Content
    1. Concepts and operations of collections
    2. Operation of the file
    3. Features and usage of functions
    4. Parameters and Local Variables
    5. The concept of return value
    6. The basic meaning of recursion
    7. Introduction to Functional programming
    8. The concept of higher order functions
first, the concept and operation of the set

Set: A set of different elements that form a collection, which is the basic data type of Python.

Collection elements (set elements): Members that make up a collection

>>> li=[' A ', ' B ', ' C ', ' A ']>>> se =set (li) >>> seset ([' A ', ' C ', ' B '])
    • A collection object is an unordered set of hashed values: A collection member can make a dictionary key
    • Repeating elements are automatically filtered in set

Set can be regarded as a set of unordered and non-repeating elements in mathematical sense, so two sets can do the intersection and set of mathematical meanings.

s = set ([3,5,9,10])      #创建一个数值集合    t = set ("Hello")         #创建一个唯一字符的集合  A = T | s          # t and S of the set    B = t & s
   
    # T and s    C = t–s          # differential Set (item in T, but not in s)    d = t ^ s          # symmetric difference set (items in t or S, but not both)         basic operation:    T.add (' x ') 
    # Add a    s.update ([10,37,42])  # Add multiple items in s use Remove         () to delete an item:    t.remove (' H ')      Len (s)  The length of the set    x in S  tests if X is a member of S X not in S to    test if X is  not a member of S    s.issubset (t)  s <= T  Test if s  Each of the elements in T    s.issuperset (t)  s >= T  tests if every element in T is in S    s.union (t)  s | t  returns a new set containing Each element in S and T    s.intersection (t)  S & T  returns a new set containing the common elements in S and T    s.difference (t)  s-t  Returns a new set containing an element in s but not in T    s.symmetric_difference (t)  s ^ T  returns a new set containing non-repeating elements in S and T    s.copy () 
     returns a shallow copy of the set "s"
   
second, the operation of the file

Three main steps for file operations:

    1. Opens the file with open and assigns the file handle to a variable
    2. A variety of actions to file on this assigned variable
    3. Close the file with the Close method
F=open ('/tmp/hello ', ' W ') #open (path + file name, read-write mode) #读写模式: R read-only, r+ read/write, W New (overwrites the original file), a append, b binary. Common patterns such as: ' RB ', ' WB ', ' r+b ' The types of read-write modes are: RU or Ua opens in read mode with Universal newline support (PEP 278) W Open as Write, a in append mode (starting with EOF, creating new files if necessary) r+ open in read-write mode w+ open in read-write mode (see W) A + Open (see a) RB opens the WB in binary read mode (see W) AB opens in binary append mode (see a) rb+ opens in binary reading mode (see r+) wb+ open in binary read-write mode (see w+) ab+ in binary read-write mode Open (see A +)

Attention:

1, use ' W ', if the file exists, first to empty, and then (re) create,

2, using the ' a ' mode, all the data to be written to the file is appended to the end of the file, even if you use Seek () to point to the file somewhere else, if the file does not exist, it will be created automatically.

Basic operation of the file

F.read ([size]) size unspecified returns the entire file if the file size >2 memory is problematic. F.read () returns "" (Empty string) File.readline () returns a row of File.readline ([size] Returns a list that contains a size row, and a size that does not specify that all rows will be returned to line #通过迭代器访问f. Write ("hello\n") #如果要写入字符串以外的数据, first convert him to a string. F.tell () F:print Returns an integer that represents the position of the current file pointer (that is, the number of bits to the file header). F.seek (offset, [start position]) is used to move the file pointer offset: unit: bit, can be negative starting position: 0-File header, default value; 1-current position; 2-End of file

Other syntax

def close (self): # real signature unknown;                Restored from __doc__ "" "Close the file.  A closed file cannot is used for further I/O operations.        Close () May is called more than once without error. "" "Pass Def Fileno (self, *args, **kwargs): # Real signature Unknown" "" Return the underlying file descr Iptor (an integer).  "" "Pass Def Isatty (self, *args, **kwargs): # Real signature Unknown" "" True if the file was connected to A TTY device. "" "Pass Def Read (self, size=-1): # known case of _io.                Fileio.read "" "Note that you may not be able to read it all back. Read at the most size bytes, returned as bytes.        Only makes one system call, so less data is returned than requested.        In non-blocking mode, returns None if the data is available.        Return an empty bytes object at EOF. "" "" Return "" Def readable (self, *args, **kwargs): # Real signature Unknown "" "True if File is opened In a read mode. "" "Pass Def ReadAll (self, *args, **kwargs): # Real signature Unknown '" "" Read all data from the F                Ile, returned as bytes.  In non-blocking mode, returns as much as are immediately available, or None if no data is available.        Return an empty bytes object at EOF. "" "Pass Def Readinto (self): # real signature unknown;        Restored from __doc__ "" "Same as Rawiobase.readinto ()." "" Pass #不要用, no one knows what it's for. Def seek (self, *args, **kwargs): # Real signature Unknown "" "Move to new file posit                Ion and return the file position.  Argument offset is a byte count. Optional argument whence defaults to Seek_set or 0 (offset from start of file, offset should be >= 0); Other values is seek_cur or 1 (move relative to current position, positive or negative), and seek_end or 2 (move relative to end of file, usually negative, although many platforms allow SeekiNg beyond the end of a file).        Note that not all file objects is seekable. "" "Pass Def seekable (self, *args, **kwargs): # Real signature Unknown" "" True if file supports Random-a Ccess.                "" "Pass Def Tell (self, *args, **kwargs): # Real signature Unknown '" "" Current file position.        Can raise oserror for non seekable files.  "" "Pass def truncate (self, *args, **kwargs): # Real signature unknown '" "truncate the file to at                Most size bytes and return the truncated size.        Size defaults to the current file position, as returned by Tell ().        The current file position was changed to the value of size. "" "Pass Def writable (self, *args, **kwargs): # Real signature Unknown" "" True if file is opened in a W Rite mode. "" "Pass Def write (self, *args, **kwargs): # Real signature Unknown '" "" Write bytes B to file, ret Urn Number WRitten.        Only makes one system call, so is not all of the data is written.  The number of bytes actually written is returned.        In non-blocking mode, returns None if the write would block. "" "Pass

another way to open a file-with

If opening a file with open only opens with two questions:

    1. May forget to close the file handle
    2. Is that the file read data has an exception and no processing is performed.

It's time to go with it.

With open ("/tmp/foo.txt") as file:    data = File.read ()

This allows the file handle to close itself when the with code block finishes executing. Mom never had to worry about me forgetting to close the file handle!

After Python 2.7, with also supports the management of multiple file contexts simultaneously, namely:

With open (' Log1 ') as Obj1, open (' log2 ') as Obj2:    Pass
characteristics and usage of functions

Functions are well-organized, reusable pieces of code that are used to implement a single, or associated function.

Functions can improve the modularity of the application, and the reuse of the code. You already know that Python provides a number of built-in functions, such as print (). But you can also create your own functions, which are called user-defined functions.

  Define a function

You can define a function that you want to function, and here are the simple rules:

    • The function code block begins with a def keyword followed by the function identifier name and parentheses ().
    • Any incoming parameters and arguments must be placed in the middle of the parentheses. Parentheses can be used to define parameters.
    • The first line of the function statement can optionally use the document string-for storing the function description.
    • The function contents begin with a colon and are indented.
    • return [expression] ends the function, optionally returning a value to the caller. Return without an expression is equivalent to returning None.

Grammar

def functionname (parameters):   "Function _ Document String"   function_suite   return [expression]

Example

def sayhi (str): #函数名 (parameter)    print ("Hello, I ' m str!") Sayhi () #调用函数
iv. parameters and local variables

When defining a function, we determine the name and position of the parameter, and the interface definition of the function is completed. For the caller of the function, it is sufficient to know how to pass the correct arguments and what values the function will return, and the complex logic inside the function is encapsulated and the caller does not need to know.

Python's function definitions are very simple, but flexible but very large. In addition to the required parameters that are normally defined, you can also use default parameters, variable parameters, and keyword parameters so that the interfaces defined by the function can not only handle complex parameters, but also simplify the caller's code.

Formal Parameters

Parametric the memory unit is allocated only when called, releasing the allocated memory unit immediately at the end of the call. Therefore, the formal parameter is only valid inside the function. The parameter variable can no longer be used after the function call finishes returning the keynote function.

actual Parameters

Arguments can be constants, variables, expressions, functions, and so on, regardless of the type of argument, and when a function call is made, they must have a definite value in order to pass these values to the parameter. Therefore, the parameter should be determined by the method of assignment, input and so on beforehand.

Default Parameters

When a function is called, the value of the default parameter is considered to be the default value if it is not passed in.

#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printinfo (name, age = +):   "Print any incoming string" Print   ("Name:", name   print ("Age", age)   return; #调用printinfo函数printinfo (age=50, name= "Miki");p Rintinfo (name= "Miki");

Results

Name:  mikiage  50Name:  mikiage  35
Keyword parameters

Keyword arguments are closely related to function calls, and function calls use keyword parameters to determine the values of the parameters passed in.

Using the keyword argument allows a function call when the order of the arguments is inconsistent with the Declaration, because the Python interpreter can match the parameter values with the name of the argument.

The following instance uses the parameter name when the function Printme () is called:

#!/usr/bin/python#-*-coding:utf-8-*-#可写函数说明def printinfo (name, age):   "Print any incoming string" Print   ("Name:", name) 
   print ("Age", age)   return; #调用printinfo函数printinfo (age=50, name= "Miki");

Results

Name:  mikiage  50
non-fixed parameters

If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter

#!/usr/bin/python#-*-coding:utf-8-*-# writable function Description def printinfo (arg1, *args):   "Print any incoming parameters" print   ("Output:")   Print (arg1) for   var in args:      print (VAR)   return; # call printinfo function Printinfo (70, 60, 50);p Rintinfo

Results

Output: 10 Output: 706050
Global variables and local variables

Variables defined inside a function have a local scope, which defines the owning global scope outside of the function.

Local variables can only be accessed within their declared functions, while global variables are accessible throughout the program. When a function is called, all variable names declared within the function are added to the scope. The following example:

#!/usr/bin/python#-*-Coding:utf-8-*-total = 0; # This is a global variable # writable function description def sum (arg1, arg2):   #返回2个参数的和. "   Total = Arg1 + arg2; # Total is a local variable here.   Print ("local variable within function:", total)   return #调用sum函数sum (+);p rint ("Outside the function is a global variable:", total)

Results

Inside a function is a local variable:  30 is a global variable outside the function:  0
v. The concept of return value

The return statement is used to return (return) from a function, that is, to jump out of a function. Again, we can optionally return a value from the function.

If return is not specified in the function, the return value of this function is None

def maximum (x, y):    if x > y:        return x    elif x = = y:        return ' two number equal '    else:        return Yprint (Maxim Um (2, 3))

Results

3
Vi. The basic meaning of recursion

Inside a function, you can call other functions. If a function calls itself internally, the function is a recursive function.

Take a recursive return calculation factorial (n! = 1 x 2 x 3 x ... x N) example

def fact (n):    if n==1:        return 1    return n * Fact (N-1)
introduction of Functional programming

Functional programming is a programming paradigm that treats computer operations as calculations of functions. The most important foundation of a functional programming language is the lambda calculus (calculus). And the function of the lambda calculus can accept the function as input (parameter) and output (return value). Compared with instruction programming, functional programming emphasizes that the calculation of functions is more important than the execution of instructions. In functional programming, the calculation of functions can be called at any time compared to procedural programming.

Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology.

One of the oldest examples of functional programming is the Lisp that was created in the 1958, through Lisp, which can be used with streamlined manpower. More modern examples include Haskell, clean, Erlang, and Miranda.

For example, an existing formula:

(1 + 2) * 3-4

If you are writing in a process-oriented manner:

var a = 1 + 2;var b = A * 3;var c = b-4;

If you follow function-oriented programming, you can do the following:

var result = Subtract (multiply (add), 3), 4);
Viii. Higher-order functions

A variable can point to a function, which can receive a variable, and a function can receive another function as a parameter, a function called a higher order function.

One of the simplest high-order functions:

def add (x, Y, f):    return F (x) + f (Y)

When we call add(-5, 6, abs) , Parameters x , y and f respectively receive -5 , 6 and, according to the abs function definition, we can deduce the calculation process as:

x = -5y = 6f = ABSF (x) + f (Y) ==> abs ( -5) + ABS (6) ==> 11return 11

This is the higher order function!

  

On-the-ground python "chapter III": Python Basics (iii)

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.