Introduction to Programming with Python Session 3 Notes Nick Cook, School of Computing Science, Newcastle University Contents 1. Recap if statements... 1 2. Iteration (repetition with while loops)... 3 3. Introduction to functions... 5 4. Exercises and challenges... 8 5. Resources... 8 1. Recap if statements In IDLE, open a new window and save file as ifrecap.py Type, run and test the following examples. Note the block structure. Ask for appropriate test values: case at the boundary of the condition, normal and unexpected (or exceptional) cases. Example 1: if else Test a condition, do one set of actions if it is true, otherwise do another set of actions. x = int(input('give me a number: ')) if x < 0: print(x, 'is negative') else: print(x, 'is positive') Test with 0, 1, - 1, '1' Example 2: if elif else Test a condition, do one set of actions if it is true. If it is not true but some other condition is true, do another set of actions. If neither condition is true, do another set of actions. c = input('give me a colour: ') if c == 'purple': print('i like', c) elif c == 'red': print('i prefer', c) else: print("i don't like", c) Test with 'purple', 'red', 'black', any other string Newcastle University, 2013 1
Example 2: if by itself Test a condition and do one set of actions if it is true, otherwise do nothing. n = int(input('give me a big number: ')) if n <= 100: print(n, 'is not a big number') Test with 99, 100, 101, '2000' Example 3: nested if to combine two conditions Test a condition, if it is true, test another condition, and then do something if both are true. issunny = input('is it sunny (y/n)? ') isholiday = input('is it a holiday (y/n)? ') if issunny == 'y': print('it is sunny') if isholiday == 'y': print('wear shorts') Test with (y, y), (y, n), (n, y) The above nested if is essentially asking whether two conditions are true and only performing an action if both are true. This is the equivalent of a logical and both conditions must be true to perform an action. Example 4: using and to combine conditions and avoid nested if The use of a nested if is error prone. Imagine if more than two conditions must be true to perform an action, we would have to make sure each if statement were indented to the right level to achieve the desired result. This also obscures the logic of the program. We have to read down multiple nested if statements to understand the combination of conditions that must be true for the whole condition to be true. We can use the logical and to combine conditions in a clearer and less error prone way. For example in the following, the overall condition is met if the number input is both greater than or equal to 1 and less than 11 (in the range 1 to 10). m = int(input('give me number between 1 and 10: ')) if m >= 1 and m < 11: print('well done! You gave me:', m) Test with 0, 1, 9, 10, 11. See the logical operator table in Section 6 of the notes for Session 2 for the truth table for the and operator. Example 5: using or to avoid code duplication Consider following code: c = input('give me a colour: ') if c == 'red': Newcastle University, 2013 2
print('i like that colour') elif c == 'green': print('i like that colour') else: print("i don't like that colour") The string 'I like that colour' will be output whether the input is 'red' or 'green'. We are duplicating code because more than one condition can lead to the same action. In this case we can use the logical or operator to simplify the code. c = input('give me a colour: ') if c == 'red' or c == 'green': print('i like that colour') else: print("i don't like that colour") As with the and operator, the or operator simplifies the code and makes the logic more obvious. The code is less error prone as a result. In this case, just one of a number of different conditions has to be true to perform some action. See the logical operator table in Section 6 of the notes for Session 2 for the truth table for the or operator. 2. Iteration (repetition with while loops) Use iteration to avoid repeating ourselves. Want to type a sequence of code and then have the program repeat it for us, rather than type (or even copy and paste) the sequence multiple times. Note, copy and paste is less error prone than repeat typing. Nevertheless, it can still lead to mistakes, e.g. if we change our minds about how many times some code must be executed. A while loop is one form of iteration that repeats a block of code as long as some condition is true. On whiteboard: Instead of: # execute code # execute code # execute code Use a while loop: while condition: # execute code Together as a class work through the first exercise in Section 3.2a of Mark Clarkson's book (p. 15). Class exercises Do second exercise in section 3.2a of the book (note there is a bug in the code in the book comparing a number/integer value to a string value will always be False) Newcastle University, 2013 3
Do challenge 13 in the first booklet of Python Programming Challenges using a while loop. Hint: need time and random modules (see Section 3 of notes for Session 2) and need to iterate enough time for the program to take 30 seconds in total Do challenge 15 Together as a class work through repetition in turtle, saving code in shapes.py. Work through and explain versions 1, 2 and 3 below in turn. Ask class how to construct version 2, which may lead to different termination condition for the while loop. Explain the rationale for using the sidestodraw in the termination condition in version 3. Also give brief overview of the turtle module and calling functions of a turtle. import turtle # version 1 with code duplication # version 2 with while loop turtle.color('red') while sidestodraw > 0: sidestodraw = sidestodraw - 1 # version 3: changing sidestodraw also changes the angle # which means we can draw different shapes by changing # sidestodraw while sidestodraw > 0: # the following are needed to terminate turtle drawing window = turtle.screen() window.exitonclick() Newcastle University, 2013 4
In vesion 3 above, just change the value of sidestodraw to 3 to draw a triangle or to 5 to draw a pentagon or to 6 to draw a hexagon etc. Ask class to experiment with different values for sidestodraw. 3. Introduction to functions Reusing code, putting a unit of work into a separate function (or procedure) and using it again wherever necessary. Also like sub- routines, breaking up a program into smaller component parts. Do 3.3a from book (p. 19) with class, save to file firstfunction.py. Function with more than one parameter Do following nsquared_plus_n function with class, save to file nsquaredplusn.py # function definition def nsquared_plus_n(nsquared, n): print(nsquared, '+',n,'=',nsquared + n) # main program counter = 0 while counter < 21: nsquared_plus_n(counter ** 2, counter) counter = counter + 1 Turtle draw a square function Re- open myshapes.py from Section 2 and do drawsquare function with class: Delete all code but version 3, so left with: import turtle while sidestodraw > 0: window = turtle.screen() window.exitonclick() Modify as follows: import turtle # function definition def draw_square(): while sidestodraw > 0: Newcastle University, 2013 5
sidestodraw = sidestodraw - 1 # main program draw_square() window = turtle.screen() window.exitonclick() Class exercises create a draw_triangle function and draw a red triangle create a draw_hexagon function and draw a blue hexagon The resulting program should be: import turtle # function definitions def draw_square(): def draw_triangle(): sidestodraw = 3 sidestodraw = sidestodraw - 1 def draw_hexagon(): sidestodraw = 6 sidestodraw = sidestodraw - 1 # main program draw_square() turtle.color('red') draw_triangle() Newcastle University, 2013 6
turtle.color('blue') draw_hexagon() window = turtle.screen() window.exitonclick() Question: what is the problem with the above code? Answer: code duplication the only difference between draw_square, draw_triangle and draw_hexagon is the value of sidestodraw, which is fixed/hard- coded in each function. Together with class develop a draw_shape function that can draw any equilateral shape. For draw_shape version 1 (parameterised with sidestodraw), take the draw_hexagon function, rename it to draw_shape, parameterise with sidestodraw, and delete the line that gives sidestodraw the value 6. def draw_shape(sidestodraw): draw_shape is a function that will draw any regular polygon (equilateral and equiangular) with sides of length 100. To draw different shapes just call the function with different values for the sidestodraw, e.g: # green square draw_shape(4) # red triangle turtle.color('red') draw_shape(3) # blue pentagon turtle.color('blue') draw_shape(5) Version 1 of draw_shape will only draw shapes with a fixed line length of 100. To draw shapes with different line lengths, add a parameter. Version 2 of draw_shape is called with a a number of sides to draw and a line length: def draw_shape(sidestodraw, linelength): turtle.forward(linelength) Newcastle University, 2013 7
Now we can draw shapes with different line lengths: # blue square, line length 100 turtle.color('blue') draw_shape(4, 100) # red triangle, line length 150 turtle.color('red') draw_shape(3, 150) # green pentagon, line length 50 draw_shape(5, 50) Question: what happens when the number of sides to draw is less than 3? Class exercises Change the draw_shape function to print a message to say that sidestodraw is too small for a suitable value of sidestodraw and only draw a shape if sidestodraw is greater than the value. Consider which other fixed value in the function could be parameterised to allow us to control the size of the shape. Change the function accordingly. 4. Exercises and challenges From Mark Clarkson's Introduction to Python: Section 3.2a, 3.2f challenge using a while loop, 3.3a, 3.3b and 3.3c From Python Programming Challenges: challenges 13 (using a while loop), 15 and 16 From Python Programming Challenges Book 2: challenges 2.6, 2.7 and 2.8 5. Resources Other material from Newcastle University Introduction to Python CPD: http://www.ncl.ac.uk/computing/outreach/resources/programming/python/intro2p ython Mark Clarkson's Introduction to Python resources including textbook, workbooks, example code and GCSE controlled assessment: http://www.ncl.ac.uk/computing/outreach/resources/protected/mwclarkson- resources.zip Other Python resources: http://www.ncl.ac.uk/computing/outreach/resources/programming/python/ Python Web site: http://www.python.org/ Newcastle University, 2013 8