Presentation is loading. Please wait.

Presentation is loading. Please wait.

If statements while loop for loop

Similar presentations


Presentation on theme: "If statements while loop for loop"— Presentation transcript:

1 If statements while loop for loop
Python Language If statements while loop for loop

2 Control Flow Includes elements for loops and conditionals
The loops include: The while loop The for loop Conditional includes: if-elif-else statement

3 >>> while expression : # condition must be true
statements >>> while expression : # condition must be true statements # single or block of statements condition >>> T = 40 while (T > 32) : print (“It is warm!”), T T -=2 Print (“It is freezing!”) , T If condition is true conditional code

4 while loop … Notes: The body section is made of Python statements, separated by new line Indent the body and post code at the same level The colon (:) in front of the while and else lines are required All fonts are in lower case

5 The while Loop  body >>> while (condition): # NOTE: the condition expression evaluates to true or false body # If the condition (x<y in the example) evaluates to true, it will execute the body else: # else is optional, rarely used! post-code # If condition evaluates to false, post-code will execute >>> Note: When typing in the IDLE, press enter after (x=x+2) (while the statement is highlighted), and then press backspace key to go to the beginning of the line, then press enter to execute the loop!

6 Nested while loops >>> while condition1 do something while condition2 do something else while condition3 do another thing

7 Nested while loop

8 While loop … example The return r code (at the same level as the while code) will execute when the loop is complete. The r and n are local variables because they are declared inside the function. If you want them to be available to other functions outside, we can declare them to be global, for example: global r = 1

9 Declare month as a dictionary of month and their indices.
Declare a local variable i, and use it in the while loop. Call the get () function of the dictionary to get the value for the indices (make sure to cast i into string)

10 while and else

11 Use while loop to read a list

12 Infinite loop This code infinitely prints because x is always negative
-10 .

13 The if statement if condition1 : # if true, then execute body1 body1
elif condition2 : # else if condition2 is true, execute body2 body2 elif condition3 : # else if condition 3 is true, execute body3 body3 . . # finally if this condition is true, execute body (n-1), otherwise elif condition (n-1) : body (n-1) else : # if none is true, then execute body(n) body (n)

14 if-elif-else >>> if condition1: # use colon after any statement! body1 # do this if condition is true. Notice the indentation elif condition2: # notice the colon body2 # otherwise do this … # put more elifs if needed else condition: bodyn # otherwise, if no condition was true except this, do bodyn

15 Game: print random numbers
>>> import random >>> x = random.randint(1,6) # generate random numbers between 1 and 6 >>> print x >>> if x == 6 : ... print "You win!“ # assume 6 is the winning number! ... elif x == 5 : # most often we do not use elif ... print "You almost got it. Try again!“ ... else : # most often we do not use else ... print "You lose!“ >>> import random # let’s use a while loop >>> i = 1 >>> while i <=50 : # prints all random numbers between 1 and 50 (inclusive) ... x = random.randint(1,50) ... print x ... i+=1 # this is equivalent to i= i +1 >>>

16 The pass statement In python we can use the pass statement to do nothing when there is no body. For example:

17 The break and continue statements
The break and continue are used in the body of the while loop. If break is executed, it immediately terminates the loop, and even the post code (if there is an else clause) will not execute. If continue is executed, it skips the reminder of the body, and the condition is evaluated again, starting the loop. The loops proceeds with the next item.

18 The break statement

19 The continue statement

20 The for loop >>> for item in sequence : # starts from the first element of the sequence body # is executed once for every element in the sequence else : # the else part is optional; rarely used. post-code >>> The loop iterates over every element of an object (sequence) such as a list tuple, or string. The iterating variable (i.e., item) in the loop first takes the value of the first element in the sequence and the body is executed. It then is set to the second element, and the body is executed. This goes on until the elements are finished. The break and continue are also used like in the while loop.

21 The for loop with a string

22 The for loop with a list

23 The for Loop with continue and break
The loop searches the list one item at a time. For each item in the list it continues to check to see if it is an integer. if not an integer, it skips it, and then checks to see if it divides by eight without a remainder, if it divides by 8, then it prints the message and breaks out of the loop!

24 Indentation and blocks
In Python, we use indentation to delimit the blocks of the control flow constructs. Blocks are one or more statements, separated by new lines. Statements include assignments, function calls, print function. >>> x = [2, 5, -3, 8] >>> for i in range (len(x)) : ... if x[i] < 0 : # indented once ... print ("The negative number is at index: ", i) # above is indented twice 'The negative number is at index: ‘, 2

25 More for loop It iterates in order over the items in the iterable sequence (e.g., list, tuple, string); in this case a list.

26 The range function Is used with the len () function to loop with explicit indices >>> x = [1, 3, 5, 4] >>> for i in range (len(x)) : # len() returns the length of the list (4 here) ... print (x[i]) 1 3 5 4 >>>

27 The range () function

28 range (n1, n2) Starts from n1 and goes up to n2 (i.e., exclusive)
We use it to make a list: >>> list (range(2, 6)) # makes a list in the range of 2 up to 6 [2, 3, 4, 5] >>> list (range (0, 10, 2)) # makes a list in the range of 0 up to 10, increment by 2 [0, 2, 4, 6, 8]

29 Loop with specific indices
It assigns a list of 10 items in x It uses the local i variable within the range of 1 to the length of the list using the len() function. It continues to iterate until the 10th item, after which it prints “Diamond.

30 for loop: example >>> inner_planets = ['Mercury', 'Venus', 'Earth', 'Mars'] >>> for planet in inner_planets : ... print (planet) Mercury # the planet variable is set to Mercury in 1st iteration Venus # the planet variable is set to Venus in 2nd iteration Earth Mars >>> >>> x = [3, 6, 9] >>> for n in x : ... print (n/3) 1 # the n variable is set to 3 in the 1st iteration 2 # the n variable is set to 6 in the 2nd iteration 3

31 while loop in ArcGIS add streets
>>> import arcpy >>> fc = “C:/Data/Street.gdb/roads” >>> cursor = arcpy.da.InsertCursor (fc, [“STREETNAME”]) >>> cursor.insertRow ([“Michigan”]) # (da is data access) # insert five rows: >>> cursor.arcpy.da.InsertCursor (fc, [“STREETNAME”]) >>> x = 1 >>> while x <=5 : cursor.insertRow ([“new street”]) # new row at bottom of table x+=1

32 The for loop in ArcGIS The following script uses the cursor variable in arcpy and the SearchCursor function of the arcpy.da module (da is data access) to retrieve the street names from a geodatabase table >>> import arcpy >>> fc = “C:/Data/street.gdb/roads” # assign the file path to fc >>> cursor = arcpy.da.SearchCursor (fc, [“STREETNAME”]) >>> for row in cursor : # iterates over the rows in the table print “streetname = {0}.format (row [0])” ObjectID Shape STREETNAME STREETTYPE 1 Polyline Peachtree RD 2 Barnwell AVE 3 Jimmy Carter 4 Central BLVD

33 More arcpy import arcpy fc = "c:/data/base.gdb/roads“ field = "StreetName“ cursor = arcpy.SearchCursor(fc) for row in cursor: print (row.getValue(field))

34 import arcpy fc = "c:/data/base.gdb/roads“ field = "StreetName“ cursor = arcpy.SearchCursor(fc) row = cursor.next() while row: print (row.getValue(field) )

35 List field contents for Counties. shp
List field contents for Counties.shp. Cursor sorted by State Name and Population. import arcpy # Open a searchcursor # Input: C:/Data/Counties.shp # Fields: NAME; STATE_NAME; POP2000 # Sort fields: STATE_NAME A; POP2000 D rows = arcpy.SearchCursor("c:/data/counties.shp", fields="NAME; STATE_NAME; POP2000", sort_fields="STATE_NAME A; POP2000 D") # Iterate through the rows in the cursor and print out the # state name, county and population of each. for row in rows: print("State: {0}, County: {1}, Population: {2}".format( row.getValue("STATE_NAME"), row.getValue("NAME"), row.getValue("POP2000")))


Download ppt "If statements while loop for loop"

Similar presentations


Ads by Google