Lecture+15+-+More+on+Flow

  • Upload
    ali-gh

  • View
    7

  • Download
    0

Embed Size (px)

DESCRIPTION

h

Citation preview

MECN2003: Software Development

MECN2012: Computing Skills and Software DevelopmentLecture 15:Python - More on Flow Control1116-04-2012Mr B. GrayMECN 2003while loopsOften, statements need to be repeated a number of times.initialisation statement(s)

while condition:statement(s)loop update statement(s)If necessary, to ensure loop runs at least onceIf necessary, to change variables used in calculating the condition.The while loop will run repeatedly as long as the condition is True.2Increment and Decrement OperatorsIt is very common when looping to have to increment or decrement a variable.i = i + 1or counter = counter - 2

There is a shorthand for this:i += 1or counter -= 2

3The Fibonacci Sequence

0 1 1 2 3 5 8 13 21 34 55 89 1444while Loop Example 1Terminate after data meets some condition# declare variablesx1 = 0x2 = 1

upLimit = int(input("please enter the upper limit: "))

print (x1)

while x2 = upLimit) or (uInput == 'e')Continuing condition: (x < upLimit) or (uInput != 'e')De Morgans Law:!(x or y) = !x or !y!(x and y) = !x and !y! means not.7For LoopsSometimes, the number of times a loop must be run is known (or can be easily calculated). For example, working through entries in a list.

The counter will take on values from the list one by one, in order, until it has taken on all of the values in the list.

The list may be pre-existing, or generated by a function such as range().for counter in list:statement(s)8The range() functionMatLabpython0:n[0, 1, , n]range(n)[0, 1, , n-1]i:n[i, i+1, , n]range(i,n)[i, i+1, , n-1]i:d:n[i, i+d, , n]range(i,n,d)[i, i+d, , n-1]The range([start], stop, [step]) function produces a list much like the : format in Matlab

Note that range(n) starts at 0 and ends at n-1.i.e. it has n elements, and starts with 0

9For Loops - ExampleRun for a specified number of iterations# declare first 2 termsx1 = 0x2 = 1

nTerms = int(input("Enter number of terms: "))

print("1 :", x1) # output first term only

for count in range(1, nTerms): print(count+1, ":" , x2) # output next term

temp = x1; # store previous x1 x1 = x2; # progress x1 x2 += temp; # calc new x2 from prev x1 and curr x2

Start at 1, since the first one is already printed.Use count + 1 since count ends at nTerms - 110