Introduction to Programming with Python Session 3 Notes



Similar documents
ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

Turtle Power. Introduction: Python. In this project, you ll learn how to use a turtle to draw awesome shapes and patterns. Activity Checklist

Algorithms Abstraction

Which shapes make floor tilings?

CSC 221: Computer Programming I. Fall 2011

MATHEMATICS Y3 Using and applying mathematics 3810 Solve mathematical puzzles and investigate. Equipment MathSphere

STEP 0: OPEN UP THE PYTHON EDITOR. If python is on your computer already, it's time to get started. On Windows, find IDLE in the start menu.

Shapes Bingo. More general matters which apply to the use of this unit are covered on the next page.

MSW LOGO 2. MSW LOGO is a programming language that lets you store a series of instructions on the computer.

GAP CLOSING. 2D Measurement. Intermediate / Senior Student Book

Python. KS3 Programming Workbook. Name. ICT Teacher Form. Do you speak Parseltongue?

CS177 MIDTERM 2 PRACTICE EXAM SOLUTION. Name: Student ID:

Welcome to Introduction to programming in Python

Introduction to Python

Python for Rookies. Example Examination Paper

Target To know the properties of a rectangle

Python Lists and Loops

Chapter 2 Writing Simple Programs

Chapter 2: Algorithm Discovery and Design. Invitation to Computer Science, C++ Version, Third Edition

UNIT H1 Angles and Symmetry Activities

Introduction to Computer Science I Spring 2014 Mid-term exam Solutions

Exercise 1: Python Language Basics

Year 9 mathematics test

Introduction to Computers and Programming. Testing

Paper 1. Calculator not allowed. Mathematics test. First name. Last name. School. Remember KEY STAGE 3 TIER 5 7

Grade 4 Mathematics Patterns, Relations, and Functions: Lesson 1

Geometry of 2D Shapes

The Richard Pate School. Draft Year 4 Scheme of Work for Scratch

Pseudo code Tutorial and Exercises Teacher s Version

PYTHON Basics

1. a procedure that you perform frequently. 2. Create a command. 3. Create a new. 4. Create custom for Excel.

Crash Dive into Python

Python Loops and String Manipulation

Crash Dive into Python

Grade 3 Core Standard III Assessment

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

Data Flow Diagrams. Outline. Some Rules for External Entities 1/25/2010. Mechanics

Visual Logic Instructions and Assignments

CBA Fractions Student Sheet 1

Paper Reference. Edexcel GCSE Mathematics (Linear) 1380 Paper 1 (Non-Calculator) Foundation Tier

Programming in Access VBA

Exercise 4 Learning Python language fundamentals

Which two rectangles fit together, without overlapping, to make a square?

Test Case Design Techniques

GAP CLOSING. 2D Measurement GAP CLOSING. Intermeditate / Senior Facilitator s Guide. 2D Measurement

2. How many ways can the letters in PHOENIX be rearranged? 7! = 5,040 ways.

Paper 1. Calculator not allowed. Mathematics test. First name. Last name. School. Remember KEY STAGE 3 TIER 4 6

Lecture 2 Notes: Flow of Control

Excel for Mac Text Functions

Computer Science for San Francisco Youth

Colour by Numbers Image Representation

Python 3 Programming. OCR GCSE Computing

6. Control Structures

Chapter 9: Building Bigger Programs

Numeracy Targets. I can count at least 20 objects

River Dell Regional School District. Computer Programming with Python Curriculum

Reasoning and Proof Review Questions

Chapter 5 Programming Statements. Chapter Table of Contents

Logistics. Software Testing. Logistics. Logistics. Plan for this week. Before we begin. Project. Final exam. Questions?

Mathematical Induction

11.3 Curves, Polygons and Symmetry

An Introduction to Number Theory Prime Numbers and Their Applications.

Elementary Number Theory and Methods of Proof. CSE 215, Foundations of Computer Science Stony Brook University

Computers. An Introduction to Programming with Python. Programming Languages. Programs and Programming. CCHSG Visit June Dr.-Ing.

2.3 WINDOW-TO-VIEWPORT COORDINATE TRANSFORMATION

Computer Science 217

Python Evaluation Rules

Grade 3 FCAT 2.0 Mathematics Sample Answers

FIRST GRADE MATH Summer 2011

Symbol Tables. Introduction

Fractions as Parts of a Group

Summit Public Schools Summit, New Jersey Grade Level / Content Area: Mathematics Length of Course: 1 Academic Year Curriculum: AP Computer Science A

Software Testing, Mythology & Methodologies

Test case design techniques I: Whitebox testing CISS

Monday 11 June 2012 Afternoon

The three tests of mental ability you will be asked to do at the AOSB are:

Shape Dictionary YR to Y6

Estimating Angle Measures

DISCOVERING 3D SHAPES

Goal: Practice writing pseudocode and understand how pseudocode translates to real code.

Grade 7/8 Math Circles November 3/4, M.C. Escher and Tessellations

Instructions. Information. Advice

Triangulation by Ear Clipping

Writing Control Structures

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Self-review 9.3 What is PyUnit? PyUnit is the unit testing framework that comes as standard issue with the Python system.

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

Year 9 mathematics test

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

Test case design techniques I: Whitebox testing CISS

Test Design Strategies

2 SYSTEM DESCRIPTION TECHNIQUES

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Sudoku puzzles and how to solve them

Software Testing. Quality & Testing. Software Testing

PGR Computing Programming Skills

Mathematics A *P44587A0128* Pearson Edexcel GCSE P44587A. Paper 2 (Calculator) Higher Tier. Friday 7 November 2014 Morning Time: 1 hour 45 minutes

Outline. Conditional Statements. Logical Data in C. Logical Expressions. Relational Examples. Relational Operators

Transcription:

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