Python Basic Learning Article Python control statement

Source: Internet
Author: User
Tags case statement

I. Structured programming

Structured programming is centered on modular design , and the software system to be developed is divided into several independent modules.

For the description to determine whether to touch a number is a positive, negative or zero flowchart.

650) this.width=650; "title=" 1 "alt=" 1 "src=" http://img1.51cto.com/attachment/201409/5/6459431_1409920098MNgl.jpg " "507" height= "/>"

The main method of structured programming is- top-down, gradual refinement . The need to solve the problem into a number of tasks to complete, and then the design of each task, gradually refinement.

Structured programming is divided into 3 structures:

1. Sequential structure

2. Judging structure

3. Cyclic structure

--------------------------------------------------------------------------------------------------------------- --------------------

Complementary points of knowledge:

In Python,raw_input () captures the user's original input .

The declaration of the Raw_input () function is as follows:

Raw_input ([prompt])->string

The parameter prompt is the prompt text that is output in the console prompting the user for input. The return value is a string. If you enter a number, the returned string is the one you need to call Int () before using it.

Example: Conversion of string and number types

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #字符串和数字类型的转换 x = Raw_input ("x:") x = Int (x) x = x + 1

Input () enables the user to enter a number or expression, and does not support input strings.

The declaration of the input () function is as follows:

Input ([prompt])->value

The parameter prompt is the prompt text that is output in the console prompting the user for input. Returns the value of a numeric type.

For example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #字符串和数字类型的转换 x = input ("x:") print (x) x = Raw_input ("x:") print (x)

--------------------------------------------------------------------------------------------------------------- ----------------------------

Second, conditional statements1. If statement

The IF statement is used to detect whether a condition is true. If it is, execute the code within the IF statement, otherwise skip the IF statement and execute the following code

The format of the IF statement is as follows:

if (expression): statement 1else: Statement 2

Example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #if语句 a = input ("A:") b = Input ("B: ") if (a > B): Print A," > ", b Print A," < ", b

Example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #if Else Statement a = input ("A:") b = Inpu T ("B:") if (a > B): Print A, ">", b else:print A, "<", b

Description

The ELSE clause is preceded by a colon, and the Python interpreter recognizes the code block corresponding to the ELSE clause.

2. If...elif...else Statement

The format of the If...elif...else statement is as follows:

if (expression 1): statement 1 elif (expression 2): Statement 2 ... elif (expression N): statement nelse: statement m

Example:

Score = input ("Score:"): if (score >=) and (score <=):p rint ("A") elif (score >=) and (score <=):p R Int ("B") elif (score >=) and (score <=):p rint ("C") else:print ("D")

3. Nesting of If statements

The nesting of an if statement means that one or more if statements can be included in the IF statement. The format is as follows:

if (expression 1): if (expression 2): statement 1elif (expression 3): Statement 2 ... else: statement 3 elif (expression N): ... else:.

Example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #嵌套的条件语句 x = 1 y = if (x >= 0): if (x > 0): y = 1 else:y = 0 else:y =-1 Print ("y =", y)
4. Realizing the function of switch statement

The switch statement is not available in Python, and Python can implement the switch statement functionality through a dictionary.

Here's how:

First, define a dictionary. A dictionary is a collection of key-value pairs.

Second, the Get () of the calling dictionary gets the corresponding expression.

Example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #使用字典实现switch语句 from __future__ impo RT Division x = 1 y = 2 operator = "/" result = {"+": X + y, "-": XY, "*": X * y, "/": Y/I,} print (ResU Lt.get (operator))

Output Result:

----------Python----------0.5 output completed (0 seconds)-Normal termination

Another scenario for using the switch branching statement is to create a switch class that processes the program. This approach is more complex and requires knowledge of object-oriented, for-loops, interrupt-statements, traversal, and so on.

The steps to implement are as follows:

(1) Create a switch class that inherits from the ancestor class object of Python. Calling the constructor int () initializes the string that needs to be matched and needs to define two member variables, value and fall. Value is used to hold the string that needs to be matched, fall is used to record whether the match succeeds, and the initial value is false, indicating that the match was unsuccessful. If the match succeeds, the program executes backwards.

(2) define a match () method that is used to match the case itself. There are 3 things to consider here: first, the match succeeds, followed by the default case clause that matches the failure, and finally, when the break is not used in the cases clause.

(3) override the __iter__ () method so that the switch class can be used in a loop statement when the method is defined. __ITER__ () calls the match () method for matching. Preserves the word by yield so that the function can iterate through the loop. Also, call the Stopiteration exception interrupt loop. The loops in Python are interrupted by an exception stopiteration. This allows the switch class to be constructed.

(4) write the calling code in for...in ... Use the switch class in the loop.

Example: Implementing the switch statement function

#!/usr/bin/python#-*-coding:utf-8-*-class switch (object):d EF __init__ (Self, value): # initialization requires a matching value Valueself.value = Valu E self.fall = False # Fall is true if there is no break in the matching case statement. def __iter__ (self): yield Self.match # Call the match method to return a generator raise Stopiteration # Stopiteration exception to determine whether the for loop ends Def match (self, *args): # method for simulating case clauses if self.fall or not args: # If Fall is true, then continue to execute the following clause # or the case clause has no match, then flow to the default branch. Return Trueelif self.value in args: # match succeeded Self.fall = Truereturn TrueElse: # match failed return falseoperator = "+" x = 1y = 2for C ASE in Switch (operator): # switch can only be used for the in loop if case (' + '):p rint (x + y) of Breakif case ('-'):p rint (XY) breakif case (' * '):p Rint (x * y) breakif case ('/'):p rint (x/y) breakif case (): # Default Branch Print ("")

Output Result:

----------Python----------3 output completed (0 seconds)-Normal termination

Third, the circular statement

& #160;& #160;& #160; A looping statement is a repeated execution of the same block of code. The loop statement consists of two parts: the loop body and the loop termination condition , and a set of repeated statements is called the loop body , and the terminating condition of the loop determines the number of repeated executions .

The looping statements in Python have a while statement and a for statement.

1. While Loop

The format of the while loop is as follows:

while (expression): ... else: ...

Example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #while循环 numbers = raw_input ("Enter several numbers , separated by commas: "). Split (", ") print numbers x = 0 while x < len (numbers): Print (number (x)) x + = 1

Example:

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #else子句的while循环 x = input ("Value of input x:")  i = 0 while (x! = 0): if (x > 0): x = 1 Else:x + = 1 i = i + 1 print ("%d cycles:"%i,x) else:print ("x equals 0:", x)

When using a looping statement, pay attention to the Boolean value of the loop expression to avoid the occurrence of a dead loop. The cycle of death means that the loop condition is always true.

2. For Loop

The For loop is used to iterate through a collection, accessing each item in the collection in turn.

The format for the For loop is as follows:

For variable in collection: ... else ...

For ... Loops are usually used with the range () function, and range () returns a list of for...in ... Iterates through the elements in the list.

The range () function is declared as follows:

Range ([Start,]stop[,step])->list of integers

Description

    • Range () returns a list of ascending or descending numbers, with the element value of the list determined by 3 parameters

    • The start parameter starts with a value of 0 for the list.

    • The parameter stop represents the value of the end of the list, which is indispensable

    • The parameter step represents the step, increment or decrement value each time, the default value is 1

    • Range () returns a list of ascending or descending numbers, with the element values of the list determined by the above 3 parameters. For example, the column returned by range ( -5,-1,-1) and the table is [5,4,3,2,1,0]

Example: Traversing the list generated by range (), filtering out positive, negative, and 0

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #for in statement for X in range ( -1,2): if X > 0:print ("Positive number:", x) elif x = = 0:print ("0:", x) Else:print ("Negative:", x) Else:print ("Loop End")

In the C, Java language, for statements that support the following structure:

for (expression 1; expression 2; expression 3) statement block

Python does not support such a for loop and can use a while loop to implement similar functions

x = 0while x < 5:print x x = x + 2

You can also use the For loop, using the range () function. For example:

For x in range (0,5,2):p rint x
3. Break and Continue statements

Break and continue statements are used to control the jump of a statement

(1) Break statement

The break statement can cause the program to jump out of a switch statement or end a loop statement

Example:

 #!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] #break语句可以使程序跳出switch语句 op Erator = "+" x = 1 y = 2  for case in switch (operator):      if case (' + '):           print (x + y)           break      if case ('-'):          print (x-y)            break     If Case (' * '):           print (x * y)           break      if case ('/'):         print (x/y)           break     If Case (): # Default Branch          print ("") 

In a looping structure, the break statement can end the loop prematurely

Example: Finding a user-entered value in the number of 0~99

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] # break statement x = input ("Value of input x:") y = 0 For y in range (0): if x = = Y:print ("Found number:", x) Break Else:print ("not Found")

The break statement cannot run outside the loop body or branch.

(2) Continue statement

The continue statement is used for control in loops, and when the program executes to the continue statement, the program goes to the next loop. The break statement loops directly from the terminal, while the continue statement stops the loop and enters the next loop, and the loop statement is not aborted.

#!/usr/bin/env python #-*-coding=utf-8-*-#Using GPL v2 #Author: [email protected] # break statement x = input ("Value of input x:") y = 0         For y in range (0, +): if x = = Y:print ("y =:", y) Continue else:print ("x =:", x) Break
Iv. Examples of structured programs

Bubble sort

650) this.width=650; "title=" 1[1] "alt=" 1[1] "src=" http://img1.51cto.com/attachment/201409/5/6459431_ 1409920100pv8v.jpg "370" height= "/>"

The bubbling sort program can be decomposed into two modules: the implementation function and the main function of the bubbling algorithm

650) this.width=650; "title=" 1[2] "alt=" 1[2] "src=" http://img1.51cto.com/attachment/201409/5/6459431_ 1409920102s1b2.jpg "" 615 "height=" 218 "/>

Example: Implementing a bubble sorting algorithm

#!/usr/bin/python#-*-coding:utf-8-*-def bubblesort (numbers): # The implementation of the Bubbling algorithm for J in Xrange (Len (Numbers)-1,-1,-1): For I In Xrange (j): if Numbers[i] > numbers[i+1]: # Put the number of small numbers to the top numbers[i], numbers[i+1] = numbers[i+1], numbers[i]print (numb ERS) def main (): # main function = [numbers, 9, 6] Bubblesort (numbers) if __name__ = = ' __main__ ': Main ()

Output Result:

----------python2.7----------[12, 23, 9, 15, 6][12, 9, 23, 15, 6][12, 9, 15, 23, 6][12, 9, 15, 6, 23][9, 12, 15, 6, 23][ 9, 12, 15, 6, 23][9, 12, 6, 15, 23][9, 12, 6, 15, 23][9, 6, 12, 15, 23][6, 9, 12, 15, 23] output complete (0 seconds)-Normal termination

Python Basic Learning Article Python control statement

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.