Summary of usage of condition judgment statements and loop statements in Python

Source: Internet
Author: User
This article mainly introduces the usage Summary of condition judgment statements and loop statements in Python. Condition statements and loop statements are the basis of Python program flow control. For more information, see If statement

> General Format
The if statement is generally in the following format:

if 
 
  : 
  
   elif 
   
    : 
    
     else: 
     
    
   
  
 

Note that there is no switch/case statement in Python.


While Loop

The while statement is the most common iteration structure in Python. In short, as long as the top test calculates the true value, a statement block is repeatedly executed.

> General Format

While
 
  
:
  
   
Else:
   
    
> Break, continue, pass, and loop else
   
  
 

Break

Jump out of the nearest loop (skip the entire loop Statement ).

Continue

Jump to the beginning of the last loop (to the first line of the loop ).

Pass

Do nothing, just an empty placeholder statement.

Loop else Block

The statement is executed only when the current loop normally leaves (that is, the break statement is not met)

> General loop format
After the break and continue statements are added, the while format is changed:

while 
 
  : 
  
    if 
   
    :break if 
    
     :continueelse: 
     
      >>pass
     
    
   
  
 

A pass statement is a placeholder without operation. It can be used when the syntax requires a statement and no practical statement can be written.

> Loop else
The syntax for adding else To the while statement is not the same as that in C/C ++. Here is a detailed description. The code after else is executed only when the loop ends normally. If the loop jumps out with the break, this part of the code will not run. For details, refer to an example of quality quantity:

x = y // 2while x > 1: if y % x == 0:  print(y,'has factor',x)  break x -= 1else: print(y,'is prime')

Let's look at another example. If else is not used:

Found = Falsewhile x and not found: if (matchx [0]): print ('ni') found = True else: x = x [1:] if not found: print ('not found') When else is used: while x: if (match (x [0]): print ('ni') breakelse: print ('not found ')

For Loop

A for Loop is a common sequence iterator in Python: It can traverse elements in any ordered sequence object. The for statement can be used for strings, lists, tuples, and other built-in iteratable objects.

> General Format

For
 
  
In
  :
   
    
Else:
    
     

The role of else here is the same as that in the while statement. In addition, when Python runs a for loop, the elements in the sequence object are assigned to the target one by one, and then the loop body is executed for each element.

Loop writing skills

Built-in range Function: returns a series of consecutive integers, which can be used as an index in.
Built-in zip function: returns the list of tuples of parallel elements. It can be used to traverse several series in.
> Cyclic counters: while and range
Range

When the range function has only one parameter, it returns an integer list from zero, but does not include the value of this parameter. If two parameters are input, the first parameter is the upper boundary and the second parameter is the lower boundary. If three parameters are input, the third parameter indicates the step value.

Range provides a simple method to repeat a specific number of actions:

for i in range(5): print(i,'Pythons')

The corresponding C ++ code is:

Int I; for (I = 0; I <5; ++ I) {std: cout <
      
       

> Parallel traversal: zip and map
Zip retrieves one or more sequences as parameters, returns the list of tuples, and matches the side-by-side elements in these sequences into pairs.

L1=[1,2,3,4]L2=[5,6,7,8]list(zip(L1,L2))

The execution result of the above Code is:

[(1,5),(2,6),(3,7),(4,8)]

When the parameter length is different, zip will take the length of the shortest sequence as the standard to cut the obtained tuples.

Use zip to construct a dictionary:

keys=['spam','eggs','totast']values=[1,2,5]D = dict(zip(keys,values))

> Offset and element: enumerate
The enumerate function is a relatively new built-in function that can return both the element value and the offset value:

s='spam'for (offset,item) in enumerate(s): print(item,'appears at offset',offset)

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.