Python Programming Exercises 3

Size: px
Start display at page:

Download "Python Programming Exercises 3"

Transcription

1 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 expressions, conditional statements and defining functions. If you did not finish the previous set of exercises you really should finish those before moving on to this set. 1. Lists are declared using square brackets with the elements of the list separated by commas. Lists can hold an arbitrary number of values which can be of different types. We use the len( ) function to discover the number of elements in a list. Try these examples: >>> len([]) >>> len([0, 1, 2, 3, 4]) >>> len(["a", 1, []]) 2. Lists can be added together and multiplied by an integer: >>> x = [1, 2, 3] + [4, 5, 6] >>> y = ["a"] * 3 We can use the inline versions of addition and multiplication if the list has already been declared: >>> x += [7, 8, 9] >>> y *= 2 3. We can append individual items to an existing list using the append( ) method: 1

2 >>> x = [] >>> x.append(1) >>> x.append(2) Multiple items can be added using the extend( ) method: >>> x = [] >>> x.extend([1, 2]) 4. You must be careful with assignment of lists because, unlike variables that contain simple values, the contents of the list is not copied, just a reference to the list: >>> x = [] >>> y = x >>> x.append(1) >>> x == y If it is not your intention to have two variables pointing to the same list, then you must use the copy( ) method: >>> x = [] >>> y = x.copy() >>> x.append(1) >>> x!= y It is very important you understand the difference between these two examples! 5. We can find out if a list contains a value using the in operator, just like we did last time for strings: >>> x = [1, 1, 1, 2, 3, 3, 5] >>> 2 in x >>> 4 in x and find the number of occurances of a value with count( ): 2

3 >>> x.count(1) Write a function called append non dup(mylist, element) that accepts two arguments, a list (mylist) and another variable (element) that can be of any type. The function should only append element to mylist if it is not already present in the list (so the list does not contain any duplicate values). Does your function return the list? Does it matter to the result? Is returning the list a good idea? 6. The ordering of elements in a list does not change unless we reorder them explicitly. This is important because we want to use integers to index elements in the list directly. Programming languages tend to start counting from zero, so the first element in the list is found at index 0, the second element at index 1, etc: >>> x = [1, 2, 3, 4, 5] >>> x[0] >>> x[1] In Python you can additionally access elements with negative numbers, for example, the last element in the list has index -1. This is useful because then we do not need to calculate the length of the list to calculate the correct index: >>> x[-1] >>> x[len(x) - 1] # unnecessary! Your answer from the previous question prevents duplicates from being appended to a list. Rewrite your function to reject consecutive duplicates, i.e. it should work like this: x = [] append_non_dup(x, 1) append_non_dup(x, 2) append_non_dup(x, 2) append_non_dup(x, 1) if x == [1,2,1] : print("correct!") 3

4 7. Elements can be removed from a list by value using the remove( ) method or by index using the del keyword: >>> x = [1,1,2,2,3,3] >>> x.remove(3) # removes first 3 in the list >>> del x[-1] # removes the element at index -1 (the last one) What happens if you try to remove a value not present in the list or using an index outside of the range of the list? 8. As well as single values we can access subsets of the list. In Python these are called slices. Assume we have a list called x: >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and two integers to use as indices: slice start and slice end: >>> slice_start = 3 >>> slice_end = 6 We can extract the slice from index slice start (inclusive) to the end of the list: >>> x[slice_start : ] From the start of the list up to index slice end (exclusive): >>> x[ : slice_end] And, finally, from slice start (inclusive) to slice end (exclusive): >>> x[slice_start : slice_end] Make sure you understand how this works by doing a few more examples yourself. The following code helps to demonstrate why the start of the slice is inclusive and the end of the slice is exclusive (because using the same index will neatly split the list in two non-overlapping lists): 4

5 >>> x = [0,1,2,3,4,5] >>> x == x[:3] + x[3:] 9. All Python scripts have a predefined list called argv in the sys module, which contains all command line arguments given to a script when it is run: import sys print(len(sys.argv), "command line arguments") print(sys.argv) Copy the code above to a file (I have called my version argv.py ) and run it with some arguments: python3 argv.py hello world Change the script above to only print out the command line arguments after the name of the script (to understand what I mean, run the example). 10. There are two methods to sort a list into order. For both methods to work all elements in the list must be orderable (i.e. values that can be compared with (==, <, <=, >, >=). The sort( ) method will sort a list in place, whereas the sorted( ) function returns a new list: >>> x = [2,5,1,3,4] >>> y = x.copy() >>> y.sort() >>> z = sorted(x) Both methods accept the reverse parameter to sort in reverse order: >>> sorted([2,5,1,3,4], reverse=true) 5

6 Python already has two functions called min( ) and max( ) that (as you would expect) returns the minimum and maximum values, respectively, from a list. Reimplement min( ) and max( ) using one of the sorting procedures. Which one is better for this problem: sort( ) or sorted( )? Why? 11. For loops in Python should be read as for each element in the sequence. The body of the for loop is executed once per item in the sequence (unless we interrupt it, see next exercises). numbers = [0,1,2,3,4] for i in numbers : Change the example above to only print out even numbers (Hint: you will need to use the modulus % operator). 12. Iterating over ranges of integers is such a common need that Python provides a special function called range( ) for that purpose: for i in range(10) : Change the code above to print out a triangle of asterisks, like this: * ** *** **** ***** 13. The range( ) function can accept two integers, a starting value (inclusive) and a stopping value (exclusive) : 6

7 for i in range(3, 10) : range( ) can also optionally take a third argument specifying a step value (i.e. only return every n th value in a given range). Try an example using a step value of Suppose we want to be able to associate the i th element in a list with the index i. Iterating through the list does not give us the index, but we can use len as the argument to range to generate a list of indices for use in our list: x = ["a", "b", "c", "d", "e", "f"] for i in range(len(x)) : print(i, x[i]) Change the example to only print out values at even numbered indices. Do not use an if statement, use the step argument in range( ). 15. Sometimes we do not want to iterate over all elements in a list, but stop when some condition is met (break out of the loop): x = [0,1,2,3,4,5,6,7,8,9] for i in x : if i > 4 : break Or skip the rest of the statements in the body of the loop (continue from the beginning): 7

8 x = [0,1,2,3,4,5,6,7,8,9] for i in x : if i > 3 and i < 6 : continue Play around with these two examples to ensure you understand what code is executed and why. In the case of a for loop, break and continue can always be replaced by different conditional statements, but using them can make your code more readable. Rewrite both examples without using either break or continue to prove this to yourself. 16. The sum( ) function returns the summation of a list of numbers: >>> sum([1,2,3]) Use the sum function to write a function called mean(x) that accepts a list of numbers as an argument and returns the arithmetic mean. Hint: the arithmetic mean for the values a 1, a 2,..., a n is 1 n ni=1 a i 17. Write your own version of sum( ) (you should call it something else). 18. Write a function that accepts a list of numbers as an argument and returns a new list where each value has been normalised (i.e. all elements sum to 1.0 in the same relative proportions as the input list). >>> normalise([1, 1, 2]) == [0.25, 0.25, 0.5] 8

9 19. Here we use a function called randint(x, y) from the random module which returns a random integer between x and y (inclusive) to implement a simple guessing game: import random r = random.randint(1, 10) print("guess a number between 1 and 10 (you have three guesses).") for i in range(1, 4) : guess = int(input("guess " + str(i) + ": ")) if guess == r : print("correct!") break else : print("wrong.") print("the number was " + str(r)) Write a new version of this program, but where the computer attempts to guess the number you are thinking of. 9

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

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

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments Chapter 6: List What we will learn: List definition Syntax for creating lists Selecting elements of a list Selecting subsequence of a list What you need to know before: Data types Assignments List Sub-list

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

DM502 Programming A. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp. DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/! PROJECT PART 1 2 Organizational Details 2 possible projects, each consisting of 2 parts for 1 st part,

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid: 1 STRINGS Objectives: How text data is internally represented as a string Accessing individual characters by a positive or negative index String slices Operations on strings: concatenation, comparison,

More information

Using Lists (Arrays) Notes

Using Lists (Arrays) Notes Using Lists (Arrays) Notes - 27.11.16 Array/List = a data structure that allows for multiplied items or elements to be stored using just one variable name. Each element in a list is accessed using an index

More information

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

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 4 1 Objectives To come back on the notion of object and type. To introduce to the

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Week 02 Module 06 Lecture - 14 Merge Sort: Analysis Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Week 02 Module 06 Lecture - 14 Merge Sort: Analysis So, we have seen how to use a divide and conquer strategy, we

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ HANDLING TEXT FILES 2 Reading Files open files

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

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

ENGR/CS 101 CS Session Lecture 12

ENGR/CS 101 CS Session Lecture 12 ENGR/CS 101 CS Session Lecture 12 Log into Windows/ACENET (reboot if in Linux) Use web browser to go to session webpage http://csserver.evansville.edu/~hwang/f14-courses/cs101.html Right-click on lecture12.py

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

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

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter

You Need an Interpreter! Comp Spring /28/08 L10 - An Interpreter You Need an Interpreter! Closing the GAP Thus far, we ve been struggling to speak to computers in their language, maybe its time we spoke to them in ours How high can we rasie the level of discourse? We

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

More information

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j;

General Syntax. Operators. Variables. Arithmetic. Comparison. Assignment. Boolean. Types. Syntax int i; float j = 1.35; int k = (int) j; General Syntax Statements are the basic building block of any C program. They can assign a value to a variable, or make a comparison, or make a function call. They must be terminated by a semicolon. Every

More information

Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14

Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14 Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14 Scan Converting Lines, Circles and Ellipses Hello everybody, welcome again

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

CS1110 Lab 6 (Mar 17-18, 2015)

CS1110 Lab 6 (Mar 17-18, 2015) CS1110 Lab 6 (Mar 17-18, 2015) First Name: Last Name: NetID: The lab assignments are very important and you must have a CS 1110 course consultant tell CMS that you did the work. (Correctness does not matter.)

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

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

If Statements, For Loops, Functions

If Statements, For Loops, Functions Fundamentals of Programming If Statements, For Loops, Functions Table of Contents Hello World Types of Variables Integers and Floats String Boolean Relational Operators Lists Conditionals If and Else Statements

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

PLT Fall Shoo. Language Reference Manual

PLT Fall Shoo. Language Reference Manual PLT Fall 2018 Shoo Language Reference Manual Claire Adams (cba2126) Samurdha Jayasinghe (sj2564) Rebekah Kim (rmk2160) Cindy Le (xl2738) Crystal Ren (cr2833) October 14, 2018 Contents 1 Comments 2 1.1

More information

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013 CS61A Lecture 16 Amir Kamil UC Berkeley February 27, 2013 Announcements HW5 due tonight Trends project due on Tuesday Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Programming Fundamentals and Python

Programming Fundamentals and Python Chapter 2 Programming Fundamentals and Python This chapter provides a non-technical overview of Python and will cover the basic programming knowledge needed for the rest of the chapters in Part 1. It contains

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

Python Problems MTH 151. Texas A&M University. November 8, 2017

Python Problems MTH 151. Texas A&M University. November 8, 2017 Python Problems MTH 151 Texas A&M University November 8, 2017 Introduction Hello! Welcome to the first problem set for MTH 151 Python. By this point, you should be acquainted with the idea of variables,

More information

Introduction to Programming with Python Session 5 Notes

Introduction to Programming with Python Session 5 Notes Introduction to Programming with Python Session 5 Notes Nick Cook, School of Computing Science, Newcastle University Contents 1. Modifications to the draw_shape function... 1 2. Positional and named parameters...

More information

Python workshop. Week 4: Files and lists.

Python workshop. Week 4: Files and lists. Python workshop Week 4: Files and lists barbera@van-schaik.org Overview of this workshop series Week 1: Writing your first program Week 2: Make choices and reuse code Week 3: Loops and strings Week 4:

More information

Excerpt from "Art of Problem Solving Volume 1: the Basics" 2014 AoPS Inc.

Excerpt from Art of Problem Solving Volume 1: the Basics 2014 AoPS Inc. Chapter 5 Using the Integers In spite of their being a rather restricted class of numbers, the integers have a lot of interesting properties and uses. Math which involves the properties of integers is

More information

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie

21-Loops Part 2 text: Chapter ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie 21-Loops Part 2 text: Chapter 6.4-6.6 ECEGR 101 Engineering Problem Solving with Matlab Professor Henry Louie While Loop Infinite Loops Break and Continue Overview Dr. Henry Louie 2 WHILE Loop Used to

More information

Programming Training. Main Points: - More Fundamental algorithms on Arrays. - Reading / Writing from files - Problem Solving

Programming Training. Main Points: - More Fundamental algorithms on Arrays. - Reading / Writing from files - Problem Solving Programming Training Main Points: - More Fundamental algorithms on Arrays. - Reading / Writing from files - Problem Solving Functions in Python A Python program is a sequence of a functions which can be

More information

Begin to code with Python Obtaining MTA qualification expanded notes

Begin to code with Python Obtaining MTA qualification expanded notes Begin to code with Python Obtaining MTA qualification expanded notes The Microsoft Certified Professional program lets you obtain recognition for your skills. Passing the exam 98-381, "Introduction to

More information

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently. The Science of Computing I Lesson 4: Introduction to Data Structures Living with Cyber Pillar: Data Structures The need for data structures The algorithms we design to solve problems rarely do so without

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ Python is a straightforward language very simple syntax It encourages programmers to program without boilerplate (prepared) code 2 Python is completely object

More information

CSCA20 Worksheet Strings

CSCA20 Worksheet Strings 1 Introduction to strings CSCA20 Worksheet Strings A string is just a sequence of characters. Why do you think it is called string? List some real life applications that use strings: 2 Basics We define

More information

CS1 Lecture 11 Feb. 9, 2018

CS1 Lecture 11 Feb. 9, 2018 CS1 Lecture 11 Feb. 9, 2018 HW3 due Monday morning, 9:00am for #1 I don t care if you use 1, 2, or 3 loops. Most important is clear correct code for #3, make sure all legal situations are handled. Think

More information

All programs can be represented in terms of sequence, selection and iteration.

All programs can be represented in terms of sequence, selection and iteration. Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Assignment 1. Stefano Guerra. October 11, The following observation follows directly from the definition of in order and pre order traversal:

Assignment 1. Stefano Guerra. October 11, The following observation follows directly from the definition of in order and pre order traversal: Assignment 1 Stefano Guerra October 11, 2016 1 Problem 1 Describe a recursive algorithm to reconstruct an arbitrary binary tree, given its preorder and inorder node sequences as input. First, recall that

More information

1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line

1.2 Adding Integers. Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line 1.2 Adding Integers Contents: Numbers on the Number Lines Adding Signed Numbers on the Number Line Finding Sums Mentally The Commutative Property Finding Sums using And Patterns and Rules of Adding Signed

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

Scientific Computing: Lecture 3

Scientific Computing: Lecture 3 Scientific Computing: Lecture 3 Functions Random Numbers More I/O Practice Exercises CLASS NOTES Ò You should be finishing Chap. 2 this week. Ò HW00 due by midnight Friday into the Box folder Ò You should

More information

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

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

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05)

Week - 03 Lecture - 18 Recursion. For the last lecture of this week, we will look at recursive functions. (Refer Slide Time: 00:05) Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 03 Lecture - 18 Recursion For the

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Statistics Case Study 2000 M. J. Clancy and M. C. Linn

Statistics Case Study 2000 M. J. Clancy and M. C. Linn Statistics Case Study 2000 M. J. Clancy and M. C. Linn Problem Write and test functions to compute the following statistics for a nonempty list of numeric values: The mean, or average value, is computed

More information

Variables and literals

Variables and literals Demo lecture slides Although I will not usually give slides for demo lectures, the first two demo lectures involve practice with things which you should really know from G51PRG Since I covered much of

More information

Chapter 1 INTRODUCTION. SYS-ED/ Computer Education Techniques, Inc.

Chapter 1 INTRODUCTION. SYS-ED/ Computer Education Techniques, Inc. Chapter 1 INTRODUCTION SYS-ED/ Computer Education Techniques, Inc. Objectives You will learn: Facilities and features of PL/1. Structure of programs written in PL/1. Data types. Storage classes, control,

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

MITOCW watch?v=se4p7ivcune

MITOCW watch?v=se4p7ivcune MITOCW watch?v=se4p7ivcune The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To

More information

[Ch 6] Set Theory. 1. Basic Concepts and Definitions. 400 lecture note #4. 1) Basics

[Ch 6] Set Theory. 1. Basic Concepts and Definitions. 400 lecture note #4. 1) Basics 400 lecture note #4 [Ch 6] Set Theory 1. Basic Concepts and Definitions 1) Basics Element: ; A is a set consisting of elements x which is in a/another set S such that P(x) is true. Empty set: notated {

More information

Lab 09: Advanced SQL

Lab 09: Advanced SQL CIS395 - BMCC - Spring 2018 04/25/2018 Lab 09: Advanced SQL A - Use Simple Loops with EXIT Conditions In this exercise, you use the EXIT condition to terminate a simple loop, and a special variable, v_counter,

More information

(Refer Slide Time: 01:12)

(Refer Slide Time: 01:12) Internet Technology Prof. Indranil Sengupta Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture No #22 PERL Part II We continue with our discussion on the Perl

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

Any Integer Can Be Written as a Fraction

Any Integer Can Be Written as a Fraction All fractions have three parts: a numerator, a denominator, and a division symbol. In the simple fraction, the numerator and the denominator are integers. Eample 1: Find the numerator, denominator, and

More information

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python

CONDITION CONTROLLED LOOPS. Introduction to Programming - Python CONDITION CONTROLLED LOOPS Introduction to Programming - Python Generating Random Numbers Generating a random integer Sometimes you need your program to generate information that isn t available when you

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

The Dynamic Typing Interlude

The Dynamic Typing Interlude CHAPTER 6 The Dynamic Typing Interlude In the prior chapter, we began exploring Python s core object types in depth with a look at Python numbers. We ll resume our object type tour in the next chapter,

More information

ISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings

ISE 101 Introduction to Information Systems. Lecture 3 Objectives: While loops Strings ISE 101 Introduction to Information Systems Lecture 3 Objectives: While loops Strings While Loops Write a Python script that computes the sum of squares from 1 to 5. sum = 0; sum = sum + 1**2; sum = sum

More information

Spring INF Principles of Programming for Informatics. Manipulating Lists

Spring INF Principles of Programming for Informatics. Manipulating Lists Manipulating Lists Copyright 2017, Pedro C. Diniz, all rights reserved. Students enrolled in the INF 510 class at the University of Southern California (USC) have explicit permission to make copies of

More information

Name: Partner: Python Activity 9: Looping Structures: FOR Loops

Name: Partner: Python Activity 9: Looping Structures: FOR Loops Name: Partner: Python Activity 9: Looping Structures: FOR Loops Learning Objectives Students will be able to: Content: Explain the difference between while loop and a FOR loop Explain the syntax of a FOR

More information

Control Flow Structures

Control Flow Structures Control Flow Structures STAT 133 Gaston Sanchez Department of Statistics, UC Berkeley gastonsanchez.com github.com/gastonstat/stat133 Course web: gastonsanchez.com/stat133 Expressions 2 Expressions R code

More information

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries

Chapter 1. Data types. Data types. In this chapter you will: learn about data types. learn about tuples, lists and dictionaries Chapter 1 Data types In this chapter you will: learn about data types learn about tuples, lists and dictionaries make a magic card trick app. Data types In Python Basics you were introduced to strings

More information

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman 1. BASICS OF PYTHON JHU Physics & Astronomy Python Workshop 2017 Lecturer: Mubdi Rahman HOW IS THIS WORKSHOP GOING TO WORK? We will be going over all the basics you need to get started and get productive

More information

An introduction to Python

An introduction to Python supported by Abstract This guide provides a simple introduction to Python with examples and exercises to assist learning. Python is a high level object-oriented programming language. Data and functions

More information

Agenda. Strings 30/10/2009 INTRODUCTION TO VBA PROGRAMMING. Strings Iterative constructs

Agenda. Strings 30/10/2009 INTRODUCTION TO VBA PROGRAMMING. Strings Iterative constructs INTRODUCTION TO VBA PROGRAMMING LESSON5 dario.bonino@polito.it Agenda Strings Iterative constructs For Next Do Loop Do While Loop Do Loop While Do Until Loop Do Loop Until Strings 1 Strings Variables that

More information

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 08 Lists Constants Last Class We Covered More on while loops Sentinel loops Boolean flags 2 Any Questions from Last Time? 3 Today s Objectives To learn about

More information

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control

Control, Quick Overview. Selection. Selection 7/6/2017. Chapter 2. Control Chapter 2 Control, Quick Overview Control Selection Selection Selection is how programs make choices, and it is the process of making choices that provides a lot of the power of computing 1 Python if statement

More information

Programming for Experimental Research. Flow Control

Programming for Experimental Research. Flow Control Programming for Experimental Research Flow Control FLOW CONTROL In a simple program, the commands are executed one after the other in the order they are typed. Many situations require more sophisticated

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

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4.

4. Write the output that would be printed from each of the following code fragments. (8pts) x = 9 y = x / 2 print('y ==', y) +1 4. 1. Write an X To the left of each valid Python name (identifier). (4pts) a) X pyhonindetfriar c) X a_b_c_d b) 9to5 d) x*y all or none 2. Write an X To the left of each Python reserved word (keyword). (4pts)

More information

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

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

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 11 Part 1 The Department of Computer Science Objectives Chapter 11 Data Collections To understand the use of lists (arrays)

More information

To illustrate what is intended the following are three write ups by students. Diagonalization

To illustrate what is intended the following are three write ups by students. Diagonalization General guidelines: You may work with other people, as long as you write up your solution in your own words and understand everything you turn in. Make sure to justify your answers they should be clear

More information

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

C++ Reference NYU Digital Electronics Lab Fall 2016

C++ Reference NYU Digital Electronics Lab Fall 2016 C++ Reference NYU Digital Electronics Lab Fall 2016 Updated on August 24, 2016 This document outlines important information about the C++ programming language as it relates to NYU s Digital Electronics

More information

SD314 Outils pour le Big Data

SD314 Outils pour le Big Data Institut Supérieur de l Aéronautique et de l Espace SD314 Outils pour le Big Data Functional programming in Python Christophe Garion DISC ISAE Christophe Garion SD314 Outils pour le Big Data 1/ 35 License

More information