35
Python Language If statements while loop for loop

Python Language If statements while loop for loop

Embed Size (px)

Citation preview

Page 1: Python Language If statements while loop for loop

Python Language

If statementswhile loop

for loop

Page 2: Python Language If statements while loop for loop

Control Flow

• Includes elements for loops and conditionals• The loops include:

– The while loop– The for loop

• Conditional includes:– if-elif-else statement

Page 3: Python Language If statements while loop for loop

>>> while expression : # condition must be true

statements# single or block of statements

condition

conditional code

while expression :statements

If condition is true

>>> T = 40while (T > 32) :

print (“It is warm!”), TT -=2

Print (“It is freezing!”) , T

Page 4: Python Language If statements while loop for loop

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

Page 5: Python Language If statements while loop for loop

The while Loop

>>> while (condition): # NOTE: the condition expression evaluates to true or falsebody # If the condition (x<y in the example) evaluates to true, it will execute the

bodyelse: # 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!

body

Page 6: Python Language If statements while loop for loop

Nested while loops

>>> while condition1do somethingwhile condition2

do something elsewhile condition3

do another thing

Page 7: Python Language If statements while loop for loop

Nested while loop

Page 8: Python Language If statements while loop for loop

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

Page 9: Python Language If statements while loop for loop

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)

Page 10: Python Language If statements while loop for loop

while and else

Page 11: Python Language If statements while loop for loop

Use while loop to read a list

Page 12: Python Language If statements while loop for loop

Infinite loop

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

Page 13: Python Language If statements while loop for loop

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)

Page 14: Python Language If statements while loop for loop

if-elif-else

>>> if condition1: # use colon after any statement!body1 # do this if condition is true. Notice the indentation

elif condition2: # notice the colonbody2 # otherwise do this

… # put more elifs if needed else condition:

bodyn # otherwise, if no condition was true except this, do bodyn

Page 15: Python Language If statements while loop for loop

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>>>

Page 16: Python Language If statements while loop for loop

The pass statement• In python we can use the pass statement to do nothing

when there is no body. For example:

Page 17: Python Language If statements while loop for loop

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.

Page 18: Python Language If statements while loop for loop

The break statement

Page 19: Python Language If statements while loop for loop

The continue statement

Page 20: Python Language If statements while loop for loop

The for loop

>>> for item in sequence : # starts from the first element of the sequence

body # is executed once for every element in the sequenceelse : # 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.

Page 21: Python Language If statements while loop for loop

The for loop with a string

Page 22: Python Language If statements while loop for loop

The for loop with a list

Page 23: Python Language If statements while loop for loop

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!

Page 24: Python Language If statements while loop for loop

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

Page 25: Python Language If statements while loop for loop

More for loop

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

Page 26: Python Language If statements while loop for loop

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])1354>>>

Page 27: Python Language If statements while loop for loop

The range () function

Page 28: Python Language If statements while loop for loop

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]

Page 29: Python Language If statements while loop for loop

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.

Page 30: Python Language If statements while loop for loop

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 iterationVenus # the planet variable is set to Venus in 2nd iterationEarthMars>>>>>> x = [3, 6, 9]>>> for n in x :... print (n/3)1 # the n variable is set to 3 in the 1st iteration2 # the n variable is set to 6 in the 2nd iteration3

Page 31: Python Language If statements while loop for loop

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

Page 32: Python Language If statements while loop for loop

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 Polyline Barnwell AVE

3 Polyline Jimmy Carter RD

4 Polyline Central BLVD

Page 33: Python Language If statements while loop for loop

More arcpy

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

print (row.getValue(field))

Page 34: Python Language If statements while loop for loop

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

print (row.getValue(field) )row = cursor.next()

Page 35: Python Language If statements while loop for loop

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 Drows = 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")))