Python Learning Path (ii)

Source: Internet
Author: User
Tags variable scope

Python Learning Path (ii)

The following Python 3.6 is used

First, conditional statements

Simple judgment

1 if Judging Condition: 2     EXECUTE statement ... 3 Else : 4     Execute statement ...

Complex judgments

1 if Judging condition 1: 2     EXECUTE statement 1 ... 3 elif Judging condition 2: 4     EXECUTE statement 2 ... 5 elif Judging condition 3: 6     EXECUTE statement 3 ... 7 Else : 8     Execute Statement 4 ...
Second, Loop statement 2.1 while statement

As with other languages, the difference is that the else statement is more. In Python, while ... else executes an ELSE statement block when the loop condition is false.

Example:

1 count = 02 while count < 5:3    print" is less   than 5"4    count = Count + 15Else: 6    Print " Is isn't less than 5 "
2.2 For statement
1  for inch sequence: 2    Statements (s)

Else statement: In Python, for ... else means that the statement in for is no different from normal, while the statement in else is executed when the loop is executed normally (that is, for not breaking out by break), while ... else is the same. 。

1  forIinchRange (2,num):#based on the factor iteration2       ifNum%i = = 0:#determining the first factor3j=num/i#calculate a second factor4          Print '%d equals%d *%d'%(NUM,I,J)5           Break            #Jump out of the current loop6    Else:#the else part of the loop7       PrintNum'is a prime number'
2.3 break,continue Statements

Used in the While,for statement

2.4 Pass Statement

acts as a placeholder statement.

2.5 Range function
1 # represents from 0 to n-1 2 # It means from a to b-1 . 3 # indicates a to b-1, step is step

Cases:

1  for  in range (5,9):2     print(i)
Third, function
    • 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, and the parentheses can be used to define the 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.
3.1 Examples of functions
1 # Defining Functions 2 def printstr (str): 3    " print any passed-in string " 4    Print (str); 5    return ; 6 7 printstr ("name"#  function call
3.2 Passing of parameters in functions

In Python, a type belongs to an object, and a variable is of no type. strings, tuples, and numbers are immutable objects, while list,dict and so on are objects that can be modified and understood as references.

3.3 Parameters in several ways
    • Required parameters: Required arguments must be passed in the correct order, and the number of calls should be the same as when declared.
    • Keyword parameter: The keyword parameter is closely related to the function call, and the function call uses the keyword argument to determine the passed-in parameter value.
 1  #   Writable function Description  2  def   Printstr (str):  3   "  Prints any incoming string   4  print   5  return  ;  6  7  #   call printstr function  8  printme (str =  " name  " ); 
    • Default parameter: When a function is called, default parameters are used if no arguments are passed.
1 def printstr (str="moren"  ):2    " prints any incoming string  "3    print  (str); 4    return;
    • Variable length parameter: The function can handle more parameters than was originally declared.
1 def functionname ([Formal_args,] *var_args_tuple):2    " Function _ document string " 3    function_suite 4    return [Expression]

* After the variable name will hold all unnamed variable parameters, is a tuple, when there is no parameter, is an empty tuple.

3.4 Return statement

Cases:

1 def sum (arg1, arg2): 2    # returns the and of the 2 parameters. 3    Total = arg1 + arg24    return total;
3.5 lambda expression
    • Lambda is just an expression, and the function body is much simpler than def.
    • The body of a lambda is an expression, not a block of code. Only a finite amount of logic can be encapsulated in a lambda expression.
    • The lambda function has its own namespace and cannot access parameters outside its own argument list or in the global namespace.
    • Although the lambda function appears to be only a single line, it is not equivalent to a C or C + + inline function, which is designed to call small functions without consuming stack memory to increase operational efficiency.
    • Format: lambda [arg1 [, Arg2,..... argn]]:expression
1 Lambda arg1, arg2:arg1 + arg2;
3.6 Variable Scope

Only modules (module), class, and functions (Def, Lambda) in Python introduce new scopes. There are 4 types of Python scopes, namely:

    • L (local) local scope
    • In functions outside of the E (enclosing) closure function
    • G (Global) scope
    • B (built-in) built-in scopes
    • When internal scopes want to modify variables used by external scopes: global (Modify external variables) and nonlocal (modify nested scopes) keywords

Example 1:

1 num = 12def Fun ():3     global num  #  needs to be used Global keyword Declaration 4     print5     num = 1236      Print(num)

Example 2:

1 def outer (): 2     num =3     def  Inner ():4         nonlocal num   #  nonlocal keyword Declaration 5         num =6         print(num)7     Inner (8)     Print (num) 9 outer ()
Iv. iterators and generators

The iterator object is accessed from the first element of the collection until all of the elements have been accessed and finished. Iterators can only move forward without backing back. Iterators have two basic methods: ITER () and next ().

4.1 iterators
1 list=[1,2,3,4]2 it = iter (list)    #  Create iterator object 3 for inch it: 4     Print (x, end="")
4.2 Generators

Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator. In the process of calling the generator to run, the function pauses and saves all current run information every time the yield is encountered, returns the value of yield, and continues running from its current location the next time the next () method is executed.

1 ImportSYS2  3 defFibonacci (N):#Generator Function-Fibonacci4A, b, counter = 0, 1, 05      whileTrue:6         if(Counter >N):7             return8         yielda9A, B = B, A +bTenCounter + = 1 Onef = Fibonacci (10)#F is an iterator that is returned by the generator A   -  whileTrue: -     Try: the         Print(Next (f), end=" ") -     exceptstopiteration: -Sys.exit ()
Five, module

A module is a file that contains all of the functions and variables that you define, followed by a. PY name. Modules can be introduced by other programs to use functions such as functions in the module. It can be understood as a library, A/C + + include.

5.1 Import Statement

A module will only be imported once. The import module is selected from the default path, from the current working directory, or through the Sys.path in sys, to find subdirectories contained in this package.

1 import module1[, module2[,... Modulen]

Cases:

1 Import sys
5.2 From...import Statements

The FROM statement of Python lets you import a specified section from the module into the current namespace, with the following syntax:

1  from Import name1[, name2[, ... Namen]] 2  from Import # Import All Modules

This will import all the names, but the names that begin with a single underscore (_) are not in this case. In most cases, Python programmers do not use this approach, because the naming of other sources introduced may well overwrite existing definitions.

5.3 __name__ Properties

If we want the module to be introduced, we can use the __name__ property to make the block execute only when the module itself is running.

#!/usr/bin/python3#Filename:using_name.pyif __name__=='__main__':   Print('The program itself is running')#run within the module before executing theElse:   Print('I'm from a different module .')#This module is not executed until the external module is imported
5.4 Packs

A directory that contains only a file called __init__.py is considered a package, primarily to avoid the misuse of names (such as String) that inadvertently affects valid modules in the search path. In the simplest case, put an empty __init__.py on it. Of course, this file can also contain some initialization code or assign a value to the __all__ variable. Cases:

 1  #   The first form of  2  import  root directory. Level two directory. Level three directory ... Span style= "COLOR: #008000" >#   3  4  #   The second form of  5  from  Root directory. Level two directory. Level three directory ... import  corresponding function #   Import the function in the corresponding module  6  from  PackageName import  * #   Imports all modules under this directory, but generally does not use this practice  

All__ can import only the specified. PY module at Import *. The case is as follows, defined in the __init.py file

1 __all__ = [" Module 1"," Module 2"...]

Python Learning Path (ii)

Related Article

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.