2. For the If judgment of python, loop summary.

Source: Internet
Author: User

I. If Judgment.

The main function of if judgment is to make different actions and manipulate different code according to the specified conditional Expression.

If judgment can be broadly divided into three kinds, namely single branch, double branch, multi Branch.

1. Single Branch if Statement.

The Single-spoke if statement format in Python is as follows:

An If expression:

Code to execute

Here is an example:

num = 10

if num = = 10: (when The value in the NUM variable equals 10, the condition is true, execute the following print "ok" Code.) )

print ' OK '

When the NUM variable is not equal to 10, nothing is Executed.

num = 1300000

if num = = 10:

print ' OK '

In a simple summary, that is, if the single branch if statement is true, the following code is executed, and if false, nothing is Executed.



2. Dual-branch If statement (if+else).

A double-branch If statement is a conditional expression that evaluates to true if the expression executes a code, and if the expression is false, executes the code under ELSE.

The format is as Follows:

An IF condition expression:

The code that executes when the conditional expression is True.

Else

The code that executes when the conditional expression is False.


For example:

num = 1300000

if num = = 10: (when num equals 10, execute print "ok", if not equal to 10, execute print "error!")

print ' OK '

Else

print ' error! '


error!




3. Multi-Branch If statement (if + elif+elif.......+else).

A multi-branch statement first evaluates a conditional expression, if the expression is true to execute a code, and once it is not true, continues to judge whether the second conditional expression starts with elif, the second condition expression is true, and if the second conditional expression is true, executes the code below the second conditional expression, If the second conditional expression is not true, continue looking for the following elif to find a third conditional expression .... And so on, if there are no other expressions later, execute the code directly under Else (else can not write).

The format is as Follows:

An IF condition expression 1:

The code that is executed when the conditional expression 1 is True.

elif conditional Expression 2: # (conditional expression 2 is checked when conditional expression 1 is not True)

The code that is executed when the conditional expression 2 is True.

elif conditional Expression 3: # (similarly, conditional expression 3 is checked when the above conditional expression 2 is not True)

The code that is executed when the conditional expression 3 is True.

elif ........ .........

Else

Executes the code when all of the above conditional expressions are False.


Summary of the 4.if Statement.

4.1 In an if-judged expression, you can use a logical operator such as is, was not, not, and,or, and so On.

4.2 When using multiple expressions, you can use () parentheses to specify the order of precedence, and of course, parentheses can also increase the readability of conditional expressions.

4.3 An If judge has at most one else but can have more than one elif.


finally, add a little bit of knowledge about conditional expressions.

All standard objects can be used to test Boolean values, and objects of the same type can be compared to the size of the PAIR.

also, the following objects have a Boolean value equal to false!! Need special attention!

none,false,0,0.0+0.0j, "" (empty string), [] empty list, () empty tuple, {} empty dictionary.

All of the above objects are False.


5. Three-dimensional Expression.

This is not a good explanation, and if the judgment is particularly like, for example, i understand.

Print "ok" If 10000 < else "error"


Error


Print "ok" if 1 < else "error"


Ok


Two. while Loop.

A while loop is a repetition of doing something if it satisfies a certain condition.

The while loop contains two loop modes, one is the dead loop (an infinite loop) and the other is the conditional count loop.

The condition here is the conditional expression that was said Earlier.

Before talking about the two while loops, let's say the syntax of the while loop, which is the syntax format:

While conditional expression:

Code that executes when the condition is True.

# (when The condition is true, the following code is executed until the condition is false and the loop Ends.) )




Example of a 1.while count Cycle.

As a simple example, it is now necessary to use the while loop to print out 1~10 Numbers.

A = 1

While a < 11:

Print a

A + = 1

1

2

3

4

5

6

7

8

9

10


2. The cycle of death, until the end of the Day.

While True:

Print "ok"

#true is a Boolean value that represents true, and the condition is true, and the loop continues until the break jumps out or the program Terminates.

The dead loop can also be used in this way.

Tag=true

Count=0

While Tag:

if count = = 9:

Tag=false

print ' The Loop is%s '% (count)

Count+=1


3. about the else part of the while loop!

While loops in Python are somewhat different from the while loop in other programming languages, the difference is that while in Python can be the same as if, support else!

Count=0

While (count < 9):

Count+=1

if count = = 3:

print ' jumps out of this loop, that is, the code after the loop continue is no longer executed, into the next loop '

Continue

print ' The Loop is%s '% (count)

Else

print ' End '


By executing the code above, you can see that when the conditional expression after the while is false, the code in the Else code block

print ' End ' is Executed.

That is, the loop is not interrupted by a break, that is, the normal end, and then the else code block is Executed.

If the loop is interrupted by a break, the code block after else will not Execute.




Three. for Loop.

The For loop and while loop are fundamentally different, for loops is an iterative loop mechanism, while a while loop is a conditional loop.

It is most appropriate to use a for loop if you want to iterate over a set sequence or other iterative object so that each element in the sequence does the same thing Again.

Several syntax for the For loop is as Follows:

For iteration variable in iterators or other iterative sequences:

The block of code to execute


If you have a list, now you need to loop through the contents of a list, you can use a for loop to do it.

names = ["Leo", "suhaozhi", "ayumi"]

For I in Names:

Print "my name is%s"% (i)


My name is Leo

My name is Suhaozhi

My name is Ayumi


You can also iterate using an Index.

names = ["Leo", "suhaozhi", "ayumi"]

For I in range (len (names)):

Print "my name is%s"% (names[i])


You can also use the enumerate function to display the index, ordinal, of each Element.

names = ["Leo", "suhaozhi", "ayumi"]

For I,n in enumerate (names,1):

Print "index:%s name:%s"% (i,n)


Index:1 Name:leo

Index:2 Name:suhaozhi

Index:3 Name:ayumi


It simply shows that the list of iterations for the for loop method, tuples and strings is not necessary to say, the iterative method and the list is Identical.


Here's How to use a For loop to traverse a dictionary.


Four. use the For loop to traverse the Dictionary.

Just throw the dictionary into the for loop and just get all the keys in the dictionary and not be traversed with value, we can try.

D1 = {' K1 ': ' v1 ', ' K2 ': ' v2 ', ' K3 ': ' v3 '}

For I in D1:

Print I


K3

K2

K1


If you need to traverse both the key and value of a dictionary at the same time, try the items method and the Iteritems method in the Dictionary.

D1 = {' Suhaozhi ': ' 13333333333 ', ' Leo ': ' 15555555555 ', ' Eric ': ' 11111111111 '}

For n,p in D1.items ():

Print "name:%s phone_number:%s"% (n,p)


Name:suhaozhi phone_number:13333333333

Name:eric phone_number:11111111111

Name:leo phone_number:15555555555


However... In the case of a particularly large amount of data, especially not recommended is yo oh that items method to iterate, because the efficiency is too low!!! The following iteration through iterators, code execution efficiency will be higher!!

D1 = {' Suhaozhi ': ' 13333333333 ', ' Leo ': ' 15555555555 ', ' Eric ': ' 11111111111 '}

For n,p in D1.iteritems ():

Print "name:%s phone_number:%s"% (n,p)

Name:suhaozhi phone_number:13333333333

Name:eric phone_number:11111111111

Name:leo phone_number:15555555555


The biggest difference between items and Iteritems in the list is that the items method returns a list, each key-value pair in the dictionary as a tuple in the list, and Iteritems returns an iterator that, if traversed, is generated sequentially from the Iterator.


finally, the For loop in python, like the while loop, supports the else syntax, as long as all content loops are not interrupted by break, and the code block in else is executed, which is the same as While.




Five. about break and Continue.

1.break is used to completely end the loop (this layer only), jump out of all loops in the program, if there are other code below the loop, the other code will execute normally without affecting the outside of the loop Code.


I remember when I first began to touch Python programming, made a very low-level mistake, that is, always put exit () when break with .... Now we understand that the difference between exit and break, one is to completely quit the Python program, the other is to jump out of this layer of the loop!! Just this floor!!

Now we're going to loop a list with 5 numbers in the list, and loop to 3 o'clock, not traversing down, outputting an end character.

L1 = [1,2,3,4,5]

L1 = [1,2,3,4,5]

For N in L1:

Print n

if n = = 3:

Break

Print "end"


The output results are as follows:

1

2

3

End


After output to 3, break jumps out of the layer loop and then outputs End.


2.continue jumps out of the loop, jumping to the beginning of the next round of loops. (this countinue is very much used when using the while Loop.) )

There is a list that now needs to be looped, with 5 numbers in the list, and a for loop to go through each number and output to the screen once, and skip over the number 3, which can be done using Continue.

L1 = [1,2,3,4,5]

For N in L1:

if n = = 3:

Continue

Else

Print n

The output results are as follows:

1

2

4

5



Six. List derivation, Lightweight loop.

A personal understanding of the lightweight derivation in Python is the lightweight for loop that is used to generate the List.

If you want to print only those squares that are divisible by 3 within 10, you can do so by adding an if section in the Derivation:

Print [n * n for N in range (ten) if n% 3 = = 0]

[0, 9, 36, 81]



This article is from the "rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1906393

2. For the If judgment of python, loop summary.

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.