Python Learning Note 2 (Control statement)

Source: Internet
Author: User
Tags case statement

1.if conditional statements

if (expression):     statement 1else:     statement 2

2.if...elif...else Judgment Statement

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

eg

#if elif Else statementScore = float (input ("Score:"))if<= score <=100:      Print("A")elif80<= score <=90:      Print("B")elif60<= score <=80:      Print("C")Else:      Print("D")

PS: When writing an IF condition statement, avoid using nested statements as much as possible. Inconvenient to read, and may overlook some possibilities

1 # Malformed nested statements 2 x = 13 y =4if(x! = 0):5     if(x > 0): c11>6         y = 17Else:8     y = 09 Print ("y =", y)

Note: The indentation rules for Python code. code with the same indentation is treated as a block of code , then the Else statement on line 7th above corresponds to the If of line 4th. Therefore, when the x! When =0, only the case of x greater than 0 is considered.

Indent please strictly follow Python's customary notation:4 spaces, do not use tab, do not Mix tab and space, otherwise it is easy to cause syntax errors due to indentation.

Substitution Scheme for 3.switch statements

There is no switch statement in Python, so a switch statement can be constructed in other ways.

    • Implementing a switch statement through a dictionary
 from_future_ImportDivisionx= 1y= 2operator="/"result= {#define a dictionary result    "+": X +y"-": X-y"*": X *y"/": X/y}Print(Result.get (operator))
    • Create a switch class that handles the flow of the program
classswitch (object):def_init_ (self, value):#Initialize the value that needs to be matchedSelf.value =value Self.fall= False#Fall True if there is no break in the case statement that is matched to    def_iter_ (self):yieldSelf.match#call the match method to return a generator        RaiseStopiteration#Stopiteration exception to determine if the for loop is over    defMatch (self, *args):#methods for simulating case clauses        ifSelf.fallor  notArgs#if Fall is true, continue with the following case statement                                                 #or CASE clause has no match, it flows to the default branch            returnTrueelifSelf.valueinchArgs#Match SuccessSelf.fall =TruereturnTrueElse:#Match failed            returnFalseoperator="+"x= 1y= 2 forCaseinchSwitch (operator):#switch can only be used in a for in loop    ifCase'+' ):        Print(x +y) Break    ifCase'-' ):        Print(X-y) Break    ifCase'*' ):        Print(x *y) Break    ifCase'/' ):        Print(X/y) Break    ifCase ():#Default Branch        Print  ""

The Ps:switch statement caused the code to be maintained and the source code bloated. Using switch is not recommended.

4.while Cycle

 while (expression):                    #  expression error, program goes to else statement     ... else:                                 #Else also belongs to part                                 of the while loop ... # the ELSE clause is executed when the last loop finishes

Eg: (traverse the data in the numbers)

Numbers = input (" enter several numbers, separated by commas:"). Split (",")  Print= 0 while x < len (numbers):    print  (number[ X])    + = 1

5.for Cycle

 for variable   in   collection:    ...                                 elsse:# The ELSE clause is executed after the last loop, else can be omitted    ...

For...in ... 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:

class Range (object)         , range    object, Range object# Start represents the starting value of the list, the default value is 0;  Stop represents the value of the end of the list, which is indispensable;#  Step represents the step, increment or decrement each time, the default value is 1;

eg

 forXinchRange ( -1,2):    ifX >0:Print("Positive number:", X)elifx = =0:Print("0:", X)Else:        Print("Negative Number:", X)Else:    Print("End of Cycle")

6.break and Continue statements (same as C)

7. Bubble Sort Example

#Bubble SortdefBubblesort (Numbers):#implementation of bubbling algorithm     forJinchRange (len (numbers)-1,-1, 1):         forIinchRange (j):ifNumbers[i] > Numbers[i*1]:#Put a small number on the topNumbers[i], numbers[i+1] = numbers[i+1], Numbers[i]Print(Numbers)defMain ():#Main functionnumbers = [23, 12, 9, 15, 6] Bubblesort (numbers)if_name_ = ='_main_': Main ()

Python Learning Note 2 (Control statement)

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.