Python Tutorial Learning (iv)--more Control Flow Tools

Source: Internet
Author: User

4.1 If expression

As the most well-known if. You must not be unfamiliar with some of these expressions:

>>>X=Int(Raw_input("Please enter an integer:"))Please enter an integer:42>>>IfX< 0: ... x = 0 ... print  ' negative changed to zero '  ... elif x == 0: ... print  ' Zero '  ... elif x == 1: ... print  ' single '  ... else: ... print  ' more '  ... more                

If you can follow one or more of the branches, the code behaves as else or the description of the elif.toturial bacterium is explained in this way: Elif is the abbreviation of else if ...

If ... elif elif ... Can be very good as a C language inside the switch ... The alternative.

4.2.For -expression

in comparison with C or Pascal, the for length in Python is slightly different. Unlike the previous two (as for how different, only know, oops), Python inside the for expression ' iterates over the items of any Sequence ', that is, any ' thing ' that can ' iterate ' is an object that can be used as a for expression (a list or string).

>>> # Measure some strings:... words = [' Cat ', ' window ', ' defenestrate ']>>> for W in words:... Print w, len(w)... Cat 3window 6defenestrate             
The original here gives a very good chestnut, solve my previous doubts, but also blame their foundation is not strong, do not know how to use.
Here are the explanations in the original text:
If you need to modify the sequence is iterating over while inside the loop (for example to duplicate selected items), It's recommended that's first make a copy. Iterating over a sequence does not implicitly make a copy. The slice notation makes this especially convenient:
Words# Loop over a slice copy of the entire list.  Len(w6:words.  Insert(0w)... words[' defenestrate ', ' Cat ', ' window ', ' defenestrate ']         
4.3. Range () function

The built-in function rang () is used to generate a sequence of integers.

Range () has several uses,

Range (stop)

Range (start, stop[, step])

The common use is to provide a parameter stop directly, such as

Range[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]   
For example, give the beginning and the end:>>>Range(1,11)[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
For example, give the beginning, the end, and then give the step:>>>Range(0,30,5)[0, 5, 10, 15, 20, 25]>>>range (010, 3 [0, 3, 6, 9]
negative number yo yo, Spacek ... >>> range (0 -10-1 [0,-1,-2, -3, -4, -5,-6,-7,-8, -9]>>> range Span class= "Mi" >0) []>>> range (10) []
4.4. BreakandContinuestatements, andElseClauses on Loops
If you have a C language learning experience, spicy you must not be confused and confused about break and continue, simply, break is used to terminate the current layer of the loop (jump out of the current layer of the loop), continue is used to enter the current loop the next time.
Oh yes, once more~
What's strange about Python is that you can keep up with a For loop for loops (while, for).

4.5.PassStatements

Pass is nothing to do. Give a few common places

def foo ():

Pass

Class Foo (object):

Pass

If XXX:

Do something

Else

Pass

Try

# if can

Do something

Except

# Pass It

Pass

Simply put, it is, sometimes predefined a function, predefined a class but just think of the prototype skeleton, the details are still perfect, you can use a pass to occupy a bit. This way, you can pass the Pthon compile, or there will be a syntax error. First put a pass there, The back is gradually perfected.

There is also the time to write where you have to ' do something ', but there is no need to ' do something ', then you can do something ' do nothing ', like the except of a try

4.6. Defining Functions

The definition of a function in Python needs to start with the keyword def. The function name can contain alphanumeric underscores, the question of the function name, which is well worth learning.

def foo ():

Do something

Function names need to be defined just right, concise and clear, can see the function to know what to do, want to think is also excellent.

The function supports aliases, such as I have defined a function Def a_very_long_named_func ():p rint ' Hello ';

Then I can do the same for you.

f = A_very_long_named_func

When I call F (), the same will print ' Hello '

All functions are returned, and no return is returned by default.

4.7. More on defining Functions4.7.1. Default Argument Values

Specify a default value for the function's parameters

5F(arg=Iarg6F()         the point of this is that when there are no parameters to pass in, the default value will work and the default value will work when you don't have to pass in the parameter.
It is important to note that:

Important Warning: The default value is evaluated only once. This makes a difference when the default was 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:

F(al=l. ) Append(aLf(1)F(2)F(3)  

This would print

[1][12][123]

If you don't want the default to is shared between subsequent calls, you can write the function like this instead:

F(al=NoneNonel.  Append(aL
4.7.2. Keyword Arguments

When you define a function in Python, you often see functions like Def foo (request, *args, **kwargs)

It is necessary to note that *args is a list, while **kwargs is a dict

A simple chestnut to illustrate a bit

A, B, c, d = 1, 2, 3, 4

E, F, g = 5, 6, 7

def f (*args, **kwargs):

Print args, type (args)

Print Kwargs, type (Kwargs)

F (A, B, C, D, E=e, f= F, g=g, H=a)

#output

[1, 2, 3, 4] List

{' E ': 5, ' F ': 6, ' G ': 7, ' H ': 1} dict

4.7.5. Lambda Expressions

Small anonymous functions can be created with the Lambda keyword. This function returns the sum of its arguments: Lambda A, B: a+b. LAMBDA functions can be used wherever function objects is required. They is syntactically restricted to a single expression. Semantically, they is just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:

When some functions are so simple that you don't need to define a function specifically, you can use a lambda to get a temporary

>>>Pairs=[(1, ' one '), (2, ' One '), (     3, ' three '), ( 4, ' Four ')]>>> pairs.  Sort(key=Lambda pair: pair[1])>>> pairs  [(4, ' Four '), (1, ' One '), (3, ' three '), (2, ' both ')]            
Another example:
f = lambda x, y:x + y # The left side of the colon is the parameter, the value returned to the right

F (1, 2) # will get 1 and 2 and 3

4.7.6. Documentation Strings

A good code, often without the need for annotations are clear at a glance, but when the project code becomes complex, the height of the modular, nested references sometimes can be seen foggy. So proper annotations are also necessary. There's something in Python that docstring, The use of the method is marked with three quotation marks, Python will automatically show these things when appropriate, such as:

My_function(): ...     "" Does nothing , but document it. ...   No, really, it doesn ' t do anything.  "" " pass...   my_function.  __doc__ does nothing, but document it.  No, really, it doesn ' t do anything.
4.8. intermezzo:coding Style
Code style: Every language has its own code style, and so does Python. For the code style, here's a look at PEP8 and PEP20.
[pep8]http://legacy.python.org/dev/peps/pep-0008/
[pep20]http://legacy.python.org/dev/peps/pep-0020/
Attached Original:
  • Use 4-space indentation, and No tabs.

    4 Spaces is a good compromise between small indentation (allows greater nesting depth) and large indentation (easier to R EAD). Tabs introduce confusion, and is best left out.

  • Wrap lines so they don ' t exceed characters.

    This helps users with small displays and makes it possible to has several code files side-by-side on larger displays.

  • Use blank lines to separate functions and classes, and larger blocks of code inside functions.

  • When possible, put comments on a line of their own.

  • Use Docstrings.

  • Use spaces around operators and after commas, but not directly inside bracketing constructs: a = f (1, 2) c5>+ g (3, 4).

  • Name your classes and functions consistently; The Convention is to use CamelCase for classes and Lower_case_with_underscores for functions and methods . Always use self as the name of the first method argument (see A First look at Classes for more on class Es and methods).

  • Don ' t use fancy encodings If your code are meant to being used in international environments. Plain ASCII works best in any case.

Python Tutorial Learning (iv)--more Control Flow Tools

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.