Introduction to Programming with Python Session 5 Notes

Size: px
Start display at page:

Download "Introduction to Programming with Python Session 5 Notes"

Transcription

1 Introduction to Programming with Python Session 5 Notes Nick Cook, School of Computing Science, Newcastle University Contents 1. Modifications to the draw_shape function Positional and named parameters For loops A function that returns a result Square spirograph challenges Resources... 5 Appendix 1: myshape.py... 6 Appendix 2: a note on functions and abstraction... 7 Appendix 3: draw_shape using a for loop Modifications to the draw_shape function Start with: import turtle def draw_shape(sidestodraw): if sidestodraw > 2: while (sidestodraw > 0): turtle.forward(100) sidestodraw = sidestodraw 1 # main program turtle.color('green') draw_shape(3) # draw other shapes window = turtle.screen() window.exitonclick() Note, line length is fixed in the function body. Modification 1 parameterise with line length. def draw_shape(linelength, sidestodraw): if sidestodraw > 2: while (sidestodraw > 0): Newcastle University,

2 turtle.forward(linelength) sidestodraw = sidestodraw 1 # main program turtle.color('green') draw_shape(50, 3) window = turtle.screen() window.exitonclick() Modification 2 what is an appropriate limit on the value of linelength? Should be greater than 0 def draw_shape(linelength, sidestodraw): if linelength > 0 and sidestodraw > 2: while (sidestodraw > 0): turtle.forward(linelength) sidestodraw = sidestodraw 1 Test the result with linelength less than 1 and sidestodraw less than 3 2. Positional and named parameters To call a function use its name and provide the expected parameters in order, e.g.: 01 do_something() 02 do_something(myvalue) 03 do_something(myvalue1, myvalue2) Line 1 calls the version of do_something that takes no parameters. Line 2 calls the version of do_something that takes one parameter (param) and there is an implicit assignment of myvalue to param. Line 3 calls the version of do_something that takes two parameters (param1 and param2) and there is an implicit assignment of myvalue1 to param1 and myvalue2 to param2 (in the order they are passed to the function). This is called positional parameter passing the order of the parameters determines the assignment of the values that the function uses. Demonstrate using the draw_shape function: Positional parameter function call is as before: import turtle # function definition here # main program turtle.color('green') draw_shape(50, 3) win = turtle.screen() Newcastle University,

3 win.exitonclick() In Python, we can also explicitly name the values to be passed to a function the assignments are made explicit in the function call by using the actual parameter names as keywords: import turtle # function definition here # main program turtle.color('green') draw_shape(linelength = 100, sidestodraw = 4) win = turtle.screen() win.exitonclick() In this case, ordering does not matter, provided all parameters are named, e.g.: draw_shape(sidestodraw = 4, linelength = 100) 3. For loops Discuss difference between the following two while loops. # while loop from draw_shape: while sidestodraw > 0: turtle.forward(linelength) sidestodraw = sidestodraw - 1 # while loop from user_guesses: number = random.randint(1, 100) guess = 0 while guess!= number: guess = int(input('guess my number: ')) if guess == number: print('well done! My number is:', number) elif guess < number: print('sorry, my number is higher') else: print('sorry, my number is lower') We often know how many times we want to iterate through a loop (as in the draw shape example). We can use a for loop for this. Work through Section 3.2b on p.16 of Mark Clarkson's book. On whiteboard: general form of for loop for i in range([start,] stop [,step]): # do something Starting with a value for variable i of start, iterate through the loop (executing any code in the block on each iteration) until ireaches the value stop. At the end Newcastle University,

4 of each iteration, increment the value of i by step. The default value for start is 0. The default value for step is 1. Class exercises 1. In a program file, do 3.2c loop challenges on p.16 of Mark Clarkson's book. o For challenge 3 of 3.2c, write a function to calculate the times table of a positive number that is given as a parameter to the function. 2. Do 3.2f loop challenge on p.18 of Mark Clarkson's book, writing a function to calculate and print the factorial of a number given as a parameter to the function. Recap: in a loop the "loopcounter" is just a variable that is given each value in turn from the specified range. Demonstrate: for loopcounter in range(10): print(loopcounter) Range: 0 to 9 inclusive (10 iterations) Output: 0 # iteration 1: loopcounter = 0 1 # iteration 2: loopcounter = 1 2 # iteration 3: loopcounter = 2 3 # iteration 4: loopcounter = 3 4 # iteration 5: loopcounter = 4 5 # iteration 6: loopcounter = 5 6 # iteration 7: loopcounter = 6 7 # iteration 8: loopcounter = 7 8 # iteration 9: loopcounter = 8 9 # iteration 10: loopcounter = 9 Demonstrate solution to 3.2c challenge 3 (timestable.py) and challenge 3.2f (factorial.py). Question which invalid values should we check for? For times table any value < 1 is invalid For factorials any value < 0 is invalid 4. A function that returns a result It is often useful to return a value from a function. For example, the factorial function would be more useful if it returned the calculated factorial rather than just printing it. Then we could use the factorial in another calculation. Demonstrate modification of the factorial function to return the value, and using it in a calculation in the main program. Newcastle University,

5 5. Square spirograph challenges Class exercises 1. Rewrite the draw_shape function in myshape.py to use a for loop instead of a while loop (demonstrate my solution see Appendix 3). 2. Do square spirograph challenges. 6. Resources Other material from Newcastle University Introduction to Python CPD: Mark Clarkson's Introduction to Python resources including textbook, workbooks, example code and GCSE controlled assessment: resources.zip Other Python resources: Python Web site: Newcastle University,

6 Appendix 1: myshape.py """ myshape.py containing a function to draw an equilateral shape download from: programming/python/intro2python/myshapes.py Nick Cook, Newcastle University, 2013 """ import turtle # equilateral shape function def draw_shape(linelength, sidestodraw): if linelength > 0 and sidestodraw > 2: while sidestodraw >0: turtle.forward(linelength) sidestodraw = sidestodraw 1 Newcastle University,

7 Appendix 2: a note on functions and abstraction Functions allow us to organise code into reusable units of work. They also provide a higher level of abstraction. Instead of having to think about the individual instructions to draw a shape using a turtle in python, we can use a function draw_shape function to provide the abstraction of drawing a shape. Functions have a name and parameters, and can also have a return value (or result). The name and parameters are called the signature of the function. The function signature allows us to distinguish between functions that may have the same name the combination of name and parameters distinguishes one function from another. For example, here are three different functions with the same name (do_something) but with a different numbers of parameters: def do_something(): # function body does something def do_something(param): # function body does something with param # - takes a single parameter def do_something(param1, param2): # function body does something # with param1 and param2 # - takes two parameters Note: in Python a function definition begins with the def keyword. The (meaningful) name of a function gives the user an idea of what the function does but not how it does it. The user of a function does not need to know how the function performs a task. The user only needs to know what the function does (and the information they have to provide, and the information they get back if there is a result). This is abstraction. It is a good idea to document the purpose of a function (what it does but not how it does it). Newcastle University,

8 Appendix 3: draw_shape using a for loop def draw_shape(linelength, sidestodraw): if linelength > 0 and sidestodraw > 2: for i in range(sidestodraw): turtle.forward(linelength) Newcastle University,

Introduction to Programming with Python Session 4 Notes

Introduction to Programming with Python Session 4 Notes Introduction to Programming with Python Session 4 Notes Nick Cook, School of Computing Science, Newcastle University Contents 1. Challenge 6 and battleships... 1 2. Recap functions... 1 3. Draw shape function...

More information

Functionally Modular. Self-Review Questions

Functionally Modular. Self-Review Questions Functionally Modular 5 Self-Review Questions Self-review 5.1 Which names are local, which are global and which are built-in in the following code fragment? Global names: Built-in names: space_invaders

More information

Python Programming Exercises 3

Python Programming Exercises 3 Python Programming Exercises 3 Notes: These exercises assume that you are comfortable with the contents of the two previous sets of exercises including variables, types, arithmetic expressions, logical

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

More information

Turtle Graphics Conditional Statements, Loops 3#

Turtle Graphics Conditional Statements, Loops 3# Turtle Graphics Conditional Statements, Loops 3# Serdar ARITAN Biomechanics Research Group, Faculty of Sports Sciences, and Department of Computer Graphics Hacettepe University, Ankara, Turkey 1 Turtle

More information

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1

Pupil Name. Year. Teacher. Target Level. Key Stage 3 Self-Assessment Year 9 Python. Spelling Test No 3. Spelling Test No 2. Spelling Test No 1 Pupil Name Year Teacher Target Level Spelling Test No 1 Spelling Test No 2 Spelling Test No 3 1) 2) 3) 4) 5) 1) 2) 3) 4) 5) 1) 2) 3) 4) 5) Spelling Test No 4 Spelling Test No 5 Spelling Test No 6 1) 2)

More information

Control Flow: Loop Statements

Control Flow: Loop Statements Control Flow: Loop Statements A loop repeatedly executes a of sub-statements, called the loop body. Python provides two kinds of loop statements: a for-loop and a while-loop. This exercise gives you practice

More information

Lecture 20: While Loops (Sections 7.3, 7.4)

Lecture 20: While Loops (Sections 7.3, 7.4) http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 20: While Loops (Sections 7.3, 7.4) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

Draw beautiful and intricate patterns with Python Turtle, while learning how to code with Python.

Draw beautiful and intricate patterns with Python Turtle, while learning how to code with Python. Raspberry Pi Learning Resources Turtle Snowflakes Draw beautiful and intricate patterns with Python Turtle, while learning how to code with Python. How to draw with Python Turtle 1. To begin, you will

More information

a. -1 b. '-1' c. Index Error: list index out of range d. TypeError: unsupported operand type(s) for +: 'int' and 'str' e.

a. -1 b. '-1' c. Index Error: list index out of range d. TypeError: unsupported operand type(s) for +: 'int' and 'str' e. Question 1 boolexprs = [3 > 2, 0 == 0, True, False, True or False, not False] truecount = 0 for expr in boolexprs: if expr: truecount += 1 print(truecount) Hint: the line truecount += 1 does exactly the

More information

Textbook. Topic 5: Repetition. Types of Loops. Repetition

Textbook. Topic 5: Repetition. Types of Loops. Repetition Textbook Topic 5: Repetition Are you saying that I am redundant? That I repeat myself? That I say the same thing over and over again? Strongly Recommended Exercises The Python Workbook: 64, 69, 74, and

More information

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block

THE IF STATEMENT. The if statement is used to check a condition: if the condition is true, we run a block THE IF STATEMENT The if statement is used to check a condition: if the condition is true, we run a block of statements (called the if-block), elsewe process another block of statements (called the else-block).

More information

Introduction to: Computers & Programming: Review prior to 2 nd Midterm

Introduction to: Computers & Programming: Review prior to 2 nd Midterm Introduction to: Computers & Programming: Review prior to 2 nd Midterm Adam Meyers New York University Summary Procedural Matters Types of Test Questions and Sample Questions Summary of what you need to

More information

CPSC 217 Midterm (Python 3 version)

CPSC 217 Midterm (Python 3 version) CPSC 217 Midterm (Python 3 version) Duration: 60 minutes 7 March 2011 This exam has 81 questions and 14 pages. This exam is closed book. No notes, books, calculators or electronic devices, or other assistance

More information

About Variables in Python F E B 1 1 T H

About Variables in Python F E B 1 1 T H About Variables in Python F E B 1 1 T H Range of floating point numbers What is the largest floating point number in Python? Unfortunately, there is no sys.maxfloat. Here is an interesting way to find

More information

Computer and Programming: Lab 1

Computer and Programming: Lab 1 01204111 Computer and Programming: Lab 1 Name ID Section Goals To get familiar with Wing IDE and learn common mistakes with programming in Python To practice using Python interactively through Python Shell

More information

Stratford School Academy Schemes of Work

Stratford School Academy Schemes of Work Page 1 of 9 Number of weeks (between 6&8) Content of the unit Assumed prior learning (tested at the beginning of the unit) 6 This unit assumes that pupils already have some prior experience in Python or

More information

Version 2.1, July Model Answers DURATION: TWO CLASSROOM PERIODS

Version 2.1, July Model Answers DURATION: TWO CLASSROOM PERIODS Version 2.1, July 2012 Model Answers PAGE 1 OF 1 DURATION: TWO CLASSROOM PERIODS Introduction The programs below are sample solutions to the challenges and tasks provided in the main text book. These solutions

More information

LOOPS. Repetition using the while statement

LOOPS. Repetition using the while statement 1 LOOPS Loops are an extremely useful feature in any programming language. They allow you to direct the computer to execute certain statements more than once. In Python, there are two kinds of loops: while

More information

Python Instruction Booklet v5.1. Learning to use Python at Stanground Academy. Name

Python Instruction Booklet v5.1. Learning to use Python at Stanground Academy. Name Python Instruction Booklet v5.1 Learning to use Python at Stanground Academy Name Contents Contents... 1 Session 1 Introduction to Python... 2 Using the IDLE in Interactive Mode... 3 Hello World... 4 Session

More information

Condition Controlled Loops. Introduction to Programming - Python

Condition Controlled Loops. Introduction to Programming - Python Condition Controlled Loops Introduction to Programming - Python Decision Structures Review Programming Challenge: Review Ask the user for a number from 1 to 7. Tell the user which day of the week was selected!

More information

nostarch.com/pfk For bulk orders, please contact us at

nostarch.com/pfk For bulk orders, please contact us at nostarch.com/pfk For bulk orders, please contact us at sales@nostarch.com. Teacher: Date/Period: Subject: Python Programming Class: Topic: #1 - Getting Started Duration: Up to 50 min. Objectives: Install

More information

CS 100: Gates and Drawing and Turtles

CS 100: Gates and Drawing and Turtles CS 100: Gates and Drawing and Turtles Chris Kauffman Week 3-1 Logistics HW 2 due Thursday at 11:59pm Code.org plus a few additional exercises HW 3 Python programming Make sure you have access to a computer

More information

CS1114 Spring 2015 Test ONE ANSWER KEY. page 1 of 8 pages (counting the cover sheet)

CS1114 Spring 2015 Test ONE ANSWER KEY. page 1 of 8 pages (counting the cover sheet) CS1114 Spring 2015 Test ONE ANSWER KEY page 1 of 8 pages (counting the cover sheet) For the following questions, use these variable definitions a = 36 b = 3 c = 12 d = '3' What is the type and value of

More information

roboturtle Documentation

roboturtle Documentation roboturtle Documentation Release 0.1 Nicholas A. Del Grosso November 28, 2016 Contents 1 Micro-Workshop 1: Introduction to Python with Turtle Graphics 3 1.1 Workshop Description..........................................

More information

3.2 for loop. Counting Loop

3.2 for loop. Counting Loop 3.2 for loop Counting Loop A while loop is a general purpose loop that can run either a specified number of times using a counting variable, or an unknown number of times, if it's controlled by some other

More information

Unit Using Logo Year Group: 4 Number of Lessons: 4

Unit Using Logo Year Group: 4 Number of Lessons: 4 Unit 4.5 - Using Logo Year Group: 4 Number of Lessons: 4 Introduction The aim of the lessons is for the children to use Logo to follow and create simple algorithms. For the lessons, the children will need

More information

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function Due: Mar25 (Note that this is a 2-week lab) This lab must be done using paired partners. You should choose a different partner

More information

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function

Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function Lab 2: Booleans, Strings, Random Numbers, Recursion, Variables, Input function Due: Mar13 (Note that this is a 2-week lab) This lab must be done using paired partners. You should choose a different partner

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information

Self-Teach Exercises: Getting Started Turtle Python

Self-Teach Exercises: Getting Started Turtle Python Self-Teach Exercises: Getting Started Turtle Python 0.1 Select Simple drawing with pauses Click on the Help menu, point to Examples 1 drawing, counting, and procedures, and select the first program on

More information

Python Unit

Python Unit Python Unit 2 2.1 2.3 2.1: Advanced print() and input() commands 2.2: Functions and Variable Scope 2.3: Flowcharting The Dragon Realm text-based game Python 2.1 Advanced print() and input() commands Objectives

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

a. SyntaxError: invalid syntax b. 1 c. 2 d. 3 e. none of the above Question 2 aseq = [2, 1, 0, -1, -2] sum = aseq[0] + aseq[-1] + aseq[-2] print(sum)

a. SyntaxError: invalid syntax b. 1 c. 2 d. 3 e. none of the above Question 2 aseq = [2, 1, 0, -1, -2] sum = aseq[0] + aseq[-1] + aseq[-2] print(sum) Multiple choice questions 1-10 (4 points each) Question 1 boolsseen = 0 bools = [not True, not False, True, False, True and False, True or False] for expr in bools: if expr: boolsseen += 1 print(boolsseen)

More information

Visualize ComplexCities

Visualize ComplexCities Introduction to Python Chair of Information Architecture ETH Zürich February 22, 2013 First Steps Python Basics Conditionals Statements Loops User Input Functions Programming? Programming is the interaction

More information

LO: To recreate Matisse s Snail in Python

LO: To recreate Matisse s Snail in Python Name: LO: To recreate Matisse s Snail in Python Step 1: Open the Python editor IDLE and make a new document by pressing ctrl-n. Make sure you type the Python code in the blank new document and not in the

More information

Python Unit

Python Unit Python Unit 1 1.1 1.3 1.1: OPERATORS, EXPRESSIONS, AND VARIABLES 1.2: STRINGS, FUNCTIONS, CASE SENSITIVITY, ETC. 1.3: OUR FIRST TEXT- BASED GAME Python Section 1 Text Book for Python Module Invent Your

More information

Module 10: Imperative Programming, Modularization, and The Future

Module 10: Imperative Programming, Modularization, and The Future Module 10: Imperative Programming, Modularization, and The Future If you have not already, make sure you Read How to Design Programs Sections 18. 1 CS 115 Module 10: Imperative Programming, Modularization,

More information

Statements 2. a operator= b a = a operator b

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

WORKBOOK 10 ACTION GEOMETRY SQUARE AND PENTAGON

WORKBOOK 10 ACTION GEOMETRY SQUARE AND PENTAGON UCL/CAS Training for Teachers Algorithms and Programming Module 1 WORKBOOK 10 ACTION GEOMETRY SQUARE AND PENTAGON Action Geometry Unplugged: starting with the square, we explore the properties of simple

More information

Problem Solving with Python Challenges 2 Scratch to Python

Problem Solving with Python Challenges 2 Scratch to Python Problem Solving with Python Challenges 2 Scratch to Python Contents 1 Drawing a triangle... 1 2 Generalising our program to draw regular polygons in Scratch and Python... 2 2.1 Drawing a square... 2 2.2

More information

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer

We will work with Turtles in a World in Java. Seymour Papert at MIT in the 60s. We have to define what we mean by a Turtle to the computer Introduce Eclipse Create objects in Java Introduce variables as object references Aleksandar Stefanovski CSCI 053 Department of Computer Science The George Washington University Spring, 2010 Invoke methods

More information

CSE 115. Introduction to Computer Science I

CSE 115. Introduction to Computer Science I CSE 115 Introduction to Computer Science I Progress In UBInfinite? A. Haven't started B. Earned 3 stars in "Calling Functions" C. Earned 3 stars in "Defining Functions" D. Earned 3 stars in "Conditionals"

More information

Learning outcomes. COMPSCI 101 Principles of Programming. Drawing 2D shapes using Characters. Printing a Row of characters

Learning outcomes. COMPSCI 101 Principles of Programming. Drawing 2D shapes using Characters. Printing a Row of characters Learning outcomes At the end of this lecture, students should be able to draw 2D shapes using characters draw 2D shapes on a Canvas COMPSCI 101 Principles of Programming Lecture 25 - Using the Canvas widget

More information

Python - Conditional Execution

Python - Conditional Execution Python - Conditional Execution x = 5 X < 10? Yes Conditional Steps Program: print 'Smaller' x = 5 Output: if x < 10: X > 20? Yes print 'Smaller Smaller Finis print 'Bigger' if x > 20: print 'Bigger' print

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

CS106 Lab 1: Getting started with Python, Linux, and Canopy. A. Using the interpreter as a fancy calculator

CS106 Lab 1: Getting started with Python, Linux, and Canopy. A. Using the interpreter as a fancy calculator CS106 Lab 1: Getting started with Python, Linux, and Canopy Dr. Victor Norman Goals: To learn How python can be used interactively for simple computational tasks. How to run Canopy Start playing with Turtle

More information

CITS 1401 Problem Solving & Programming

CITS 1401 Problem Solving & Programming CITS 1401 Problem Solving & Programming Tim French Lecture 03 Numeric Data Processing (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives of

More information

Graphics. TUGboat, Volume 23 (2002), No. 3/4 309

Graphics. TUGboat, Volume 23 (2002), No. 3/4 309 TUGboat, Volume 23 (2002), No. 3/4 309 tool in such a situation, combining efficiency and high quality. Very often, these documents should be illustrated with geometric figures. I first used the excellent

More information

C Programming for Electronic Engineers

C Programming for Electronic Engineers C Programming for Electronic Engineers Keith Jackson BSc CEng MIEE with acknowledgement to Gavin Eamshaw MEng School of Electronic, Communication and Electrical Engineering University of Plymouth MACMILLAN

More information

CS 1301 CS1 with Robots Summer 2007 Exam 1

CS 1301 CS1 with Robots Summer 2007 Exam 1 Your Name: 1 / 6 CS 1301 CS1 with Robots Summer 2007 Exam 1 1. Vocabulary Matching: (15 points) Write the number from the correct definition in the blank next to each term on the left: _12_Print statement

More information

Last week. Another example. More recursive examples. How about these functions? Recursive programs. CSC148 Intro. to Computer Science

Last week. Another example. More recursive examples. How about these functions? Recursive programs. CSC148 Intro. to Computer Science CSC48 Intro. to Computer Science Lecture 7: Recursive Functions/Structures Trees mir H. Chinaei, Summer 206 Office Hours: R 0-2 B4222 ahchinaei@cs.toronto.edu http://www.cs.toronto.edu/~ahchinaei/ Course

More information

(Python) Chapter 3: Repetition

(Python) Chapter 3: Repetition (Python) Chapter 3: Repetition 3.1 while loop Motivation Using our current set of tools, repeating a simple statement many times is tedious. The only item we can currently repeat easily is printing the

More information

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable

RETURN X return X Returning a value from within a function: computes the value of variable exits the function and returns the value of the variable STUDENT TEACHER CLASS WORKING AT GRADE TERM TARGET YEAR TARGET Pseudocode Python Description BEGIN END Identifies the start of a program Identifies the end of a program READ X, Y, Z input() Identifies

More information

Basics of Programming with Python

Basics of Programming with Python Basics of Programming with Python A gentle guide to writing simple programs Robert Montante 1 Topics Part 3 Obtaining Python Interactive use Variables Programs in files Data types Decision-making Functions

More information

11 Data Structures Foundations of Computer Science Cengage Learning

11 Data Structures Foundations of Computer Science Cengage Learning 11 Data Structures 11.1 Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define a data structure. Define an array as a data structure

More information

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19

Outline. 1 If Statement. 2 While Statement. 3 For Statement. 4 Nesting. 5 Applications. 6 Other Conditional and Loop Constructs 2 / 19 Control Flow 1 / 19 Outline 1 If Statement 2 While Statement 3 For Statement 4 Nesting 5 Applications 6 Other Conditional and Loop Constructs 2 / 19 If Statement Most computations require different actions

More information

Honors Computer Science Python Mr. Clausen Program 7A, 7B

Honors Computer Science Python Mr. Clausen Program 7A, 7B Honors Computer Science Python Mr. Clausen Program 7A, 7B PROGRAM 7A Turtle Graphics Animation (100 points) Here is the overview of the program. Use functions to draw a minimum of two background scenes.

More information

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time

Today. CISC101 Reminders & Notes. Searching in Python - Cont. Searching in Python. From last time CISC101 Reminders & Notes Test 3 this week in tutorial USATs at the beginning of next lecture Please attend and fill out an evaluation School of Computing First Year Information Session Thursday, March

More information

Name & Recitation Section:

Name & Recitation Section: Name & Recitation Section: Due Wednesday, Jan 5 at 2:10 PM in 34-101. Please print out your code files (homework 1.py, rps.py, loops.py, and any code you wrote for optional problems), staple them to the

More information

APCS Semester #1 Final Exam Practice Problems

APCS Semester #1 Final Exam Practice Problems Name: Date: Per: AP Computer Science, Mr. Ferraro APCS Semester #1 Final Exam Practice Problems The problems here are to get you thinking about topics we ve visited thus far in preparation for the semester

More information

Python Programming: An Introduction to Computer Science

Python Programming: An Introduction to Computer Science Python Programming: An Introduction to Computer Science Chapter 3 Computing with Numbers Python Programming, 2/e 1 Objectives n To understand the concept of data types. n To be familiar with the basic

More information

ME30 Lab3 Decisions. February 20, 2019

ME30 Lab3 Decisions. February 20, 2019 ME30 Lab3 Decisions February 20, 2019 0.0.1 ME 30 Lab 4 - Conditional Program Execution ME 30 ReDev Team 2018-07-06 Description and Summary: This lab introduces the programming concept of decision-making,

More information

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us?

CS 105 Lab As a review of what we did last week a. What are two ways in which the Python shell is useful to us? 1 CS 105 Lab 3 The purpose of this lab is to practice the techniques of making choices and looping. Before you begin, please be sure that you understand the following concepts that we went over in class:

More information

Midterm Exam 1 Solutions

Midterm Exam 1 Solutions CS 61A Fall 2011 Structure and Interpretation of Computer Programs Midterm Exam 1 Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed

More information

The first print the integer literal 12, the second prints the string comprising the character 1 followed by the character 2.

The first print the integer literal 12, the second prints the string comprising the character 1 followed by the character 2. The Fundamentals 2 Self-Review Questions Self-review 2.1 What are the types of the following literals? 1, 1., 1.0, 1, 1., 1.0, 1, 1., 100000000000000000, 100000000000000000., 100000000000000000.0. int,

More information

Lecture 4. Defining Functions

Lecture 4. Defining Functions Lecture 4 Defining Functions Academic Integrity Quiz Remember: quiz about the course AI policy Have posted grades for completed quizes Right now, missing ~130 enrolled students If did not receive at least

More information

Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7

Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7 Turtle Graphics and L-systems Informatics 1 Functional Programming: Tutorial 7 Heijltjes, Wadler Due: The tutorial of week 9 (20/21 Nov.) Reading assignment: Chapters 15 17 (pp. 280 382) Please attempt

More information

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison

Media Computation. Lecture 16.1, December 8, 2008 Steve Harrison Media Computation Lecture 16.1, December 8, 2008 Steve Harrison Today -- Details of Creating Classes From requirements to classes Creating a class that will simulate a number game Practice going from requirements

More information

CS100 Spring 2017 Final

CS100 Spring 2017 Final CS100 Spring 2017 Final May 11, 2017 There are 13 questions on this test. Record your answers to the first 10 questions by circling a letter below. Answer questions 11, 12 and 13 on the attached pages.

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Getting Started 1 of 30 January 4, 2017 What You Need to Get Started? Python An object-oriented language gaining popularity in the industry IPython An interactive version of Python

More information

Program Planning, Data Comparisons, Strings

Program Planning, Data Comparisons, Strings Program Planning, Data Comparisons, Strings Program Planning Data Comparisons Strings Reading for this class: Dawson, Chapter 3 (p. 80 to end) and 4 Program Planning When you write your first programs,

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

Fractals and L- Systems

Fractals and L- Systems Fractals and L- Systems Sanyam Gupta January 26, 2018 1 Lindenmayer systems Have you ever wondered, how to formulate a mathematical equation for the plant in your verandah or garden? The nature produces

More information

Final thoughts on functions F E B 2 5 T H

Final thoughts on functions F E B 2 5 T H Final thoughts on functions F E B 2 5 T H Ordering functions in your code Will the following code work? Here the function is defined after the main program that is calling it. print foo() def foo(): return

More information

Properties of polygons Year level: 6 7

Properties of polygons Year level: 6 7 Properties of polygons Year level: 6 7 Unit of work contributed by Anne Pillman, Marryatville Primary School, SA L6558 Exploring s. Copyright Alberta Education About the unit Unit description This unit

More information

Conditional Execution

Conditional Execution Conditional Execution Chapter 3 Python for Informatics: Exploring Information www.py4inf.com Unless otherwise ted, the content of this course material is licensed under a Creative Commons Attribution 3.0

More information

The float type and more on variables FEB 6 TH 2012

The float type and more on variables FEB 6 TH 2012 The float type and more on variables FEB 6 TH 2012 The float type Numbers with decimal points are easily represented in binary: 0.56 (in decimal) = 5/10 + 6/100 0.1011 (in binary) = ½+0/4 + 1/8 +1/16 The

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

More information

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0 OCTOBER 2014 Python Selection and Conditionals 1 SELECTION AND CONDITIONALS WHAT YOU MIGHT KNOW ALREADY You will probably be familiar

More information

Functions and Recursion

Functions and Recursion Functions and Recursion Chapter 5 Prof. Mauro Gaspari: gaspari@cs.unibo.it Example import math def area(radius): temp = math.pi * radius**2 return temp # or def area(radius): return math.pi * radius**2

More information

Cambridge TECHNICALS LEVEL 3

Cambridge TECHNICALS LEVEL 3 Cambridge TECHNICALS LEVEL 3 IT MAPPING GUIDE Unit 15 Games Design and Prototyping Version 1 ocr.org.uk/it INTRODUCTION Prodigy are delighted to work with OCR, a progressive Awarding Organisation, who

More information

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1 COMPUTER SCIENCE 61A June 24, 2014 0.1 Warmup What Would Python Do? >>> x = 6 >>> def square(x):... return x * x >>> square(x) >>> max(pow(2, 3), square(-5)) -

More information

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi Shell / Python Tutorial CS279 Autumn 2017 Rishi Bedi Shell (== console, == terminal, == command prompt) You might also hear it called bash, which is the most widely used shell program macos Windows 10+

More information

7. Tile That Courtyard, Please

7. Tile That Courtyard, Please 7. Tile That Courtyard, Please We shape our buildings; thereafter they shape us. Winston Churchill. Programming constructs and algorithmic paradigms covered in this puzzle: List comprehension basics. Recursive

More information

Python 2. KS3 Programming Workbook. Name. ICT Teacher Form. Taking you Parseltongue further. Created by D.Aldred P a g e 1

Python 2. KS3 Programming Workbook. Name. ICT Teacher Form. Taking you Parseltongue further. Created by D.Aldred P a g e 1 Python 2 KS3 Programming Workbook Taking you Parseltongue further Name ICT Teacher Form Created by D.Aldred P a g e 1 To Execute the program code press F5 Welcome to Python The python software has two

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

Binary Search Tree. Revised based on textbook author s notes.

Binary Search Tree. Revised based on textbook author s notes. Binary Search Tree Revised based on textbook author s notes. Search Trees The tree structure can be used for searching. Each node contains a search key as part of its data or payload. Nodes are organized

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Structure and Interpretation of Computer Programs Fall 2011 Midterm Exam 1 INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed calculator,

More information

CONTROL FLOW CREATING ALTERNATE PATHS OF EXECUTION USING: BRANCHING WHILE LOOPS FOR LOOPS

CONTROL FLOW CREATING ALTERNATE PATHS OF EXECUTION USING: BRANCHING WHILE LOOPS FOR LOOPS CONROL LOW CREAING ALERNAE PAHS O EXECUION USING: BRANCHING WHILE LOOPS OR LOOPS CREAING ALERNAE PAHS O EXECUION Up until now our programs are sequential and execute all lines of code from top to bottom.

More information

Python lab session 1

Python lab session 1 Python lab session 1 Dr Ben Dudson, Department of Physics, University of York 28th January 2011 Python labs Before we can start using Python, first make sure: ˆ You can log into a computer using your username

More information

1 Strings (Review) CS151: Problem Solving and Programming

1 Strings (Review) CS151: Problem Solving and Programming 1 Strings (Review) Strings are a collection of characters. quotes. this is a string "this is also a string" In python, strings can be delineated by either single or double If you use one type of quote

More information

Scheme of work Cambridge International AS & A Level Computing (9691)

Scheme of work Cambridge International AS & A Level Computing (9691) Scheme of work Cambridge International AS & A Level Computing (9691) Unit 2: Practical programming techniques Recommended prior knowledge Students beginning this course are not expected to have studied

More information

Introduction to programming using Python

Introduction to programming using Python Introduction to programming using Python Matthieu Choplin matthieu.choplin@city.ac.uk http://moodle.city.ac.uk/ Session 5 1 Objectives To come back on the definition of functions To invoke value-returning

More information

Lab 4 Fruitful Functions

Lab 4 Fruitful Functions Lab 4 Fruitful Functions September 19, 2018 1 ME 30 Lab 4 - Functions and Style Description and Summary: >A function in programming is a block of code that performs some task. Functions are a way to organize

More information

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics

: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics Assignment 1: Turtle Graphics Page 1 600.112: Intro Programming for Scientists and Engineers Assignment 1: Turtle Graphics Peter H. Fröhlich phf@cs.jhu.edu Joanne Selinski joanne@cs.jhu.edu Due Date: Wednesdays

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 3 The Department of Computer Science Review of Chapter 2 Stages of creating a program: Analyze the problem Determine specifications

More information

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.

A lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions. Handout 2 Functions, Lists, For Loops and Tuples [ ] Functions -- parameters/arguments, "calling" functions, return values, etc. Please make sure you understand this example: def square(x): return x *

More information