CMSC201 Computer Science I for Majors

Similar documents
CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC 201 Spring 2019 Lab 06 Lists

CMSC 201 Spring 2017 Lab 05 Lists

CMSC201 Computer Science I for Majors

CMSC 201 Computer Science I for Majors

CMSC 201 Spring 2017 Homework 4 Lists (and Loops and Strings)

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC 341 Lecture 7 Lists

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

CMSC 201 Spring 2018

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors

2. Explain the difference between read(), readline(), and readlines(). Give an example of when you might use each.

CMSC 201 Fall 2016 Lab 09 Advanced Debugging

EECS 183. Week 3 - Diana Gage. www-personal.umich.edu/ ~drgage

CMSC 201 Fall 2018 Lab 04 While Loops

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CMSC201 Computer Science I for Majors

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

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

CMSC201 Computer Science I for Majors

CS1 Lecture 11 Feb. 9, 2018

CMSC 201 Spring 2017 Lab 01 Hello World

Algorithmic Thinking: Computing with Lists

Announcements. Lecture Agenda. Class Exercise. Hashable. Mutability. COMP10001 Foundations of Computing Iteration

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

INTERMEDIATE LEVEL PYTHON PROGRAMMING SELECTION AND CONDITIONALS V1.0

CMSC201 Computer Science I for Majors

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

SAMS Programming A/B. Lecture #1 Introductions July 3, Mark Stehlik

CMSC201 Computer Science I for Majors

Sequence Types FEB

CS 170 Java Programming 1. Week 10: Loops and Arrays

Python 2 Conditionals and loops Matthew Egbert CS111

Name & Recitation Section:

Ph3 Mathematica Homework: Week 1

CS1 Lecture 13 Feb. 13, 2019

Introduction to: Computers & Programming: Review prior to 1 st Midterm

CMSC 201 Fall 2015 Lab 12 Tuples and Dictionaries

CS 115 Lecture 13. Strings. Neil Moore. Department of Computer Science University of Kentucky Lexington, Kentucky

CS Introduction to Programming Fall 2016

CMSC 201 Spring 2018 Project 2 Battleship

Getting Started. Excerpted from Hello World! Computer Programming for Kids and Other Beginners

CMSC201 Computer Science I for Majors

CMSC 201 Spring 2017 Lab 12 Recursion

PROGRAMMING FUNDAMENTALS

CMSC 201 Fall 2016 Lab 13 More Recursion

6.189 Project 1. Readings. What to hand in. Project 1: The Game of Hangman. Get caught up on all the readings from this week!

CS 100: Computability, Python Lists

} Evaluate the following expressions: 1. int x = 5 / 2 + 2; 2. int x = / 2; 3. int x = 5 / ; 4. double x = 5 / 2.

CS1 Lecture 9 Feb. 5, 2018

COM110: Lab 2 Numeric expressions, strings, and some file processing (chapters 3 and 5)

Abstract Data Types Chapter 1

Lecture 5. Defining Functions

Python 2 Conditionals and loops

PREPARING FOR PRELIM 1

Selection Statement ( if )

CMSC 201 Spring 2018 Lab 01 Hello World

CSE 374: Programming Concepts and Tools. Eric Mullen Spring 2017 Lecture 4: More Shell Scripts

Python: common syntax

CS 303E Fall 2011 Exam 2 Solutions and Criteria November 2, Good Luck!

CS 1110, LAB 1: PYTHON EXPRESSIONS.

Lecture 20: While Loops (Sections 7.3, 7.4)

Control Structures 1 / 17

If Statements, For Loops, Functions

CS1 Lecture 5 Jan. 26, 2018

CS1 Lecture 12 Feb. 11, 2019

Text Input and Conditionals

CME 193: Introduction to Scientific Python Lecture 1: Introduction

C10552: Intro to Computation. Lecture 2 July 17, 2016

(Python) Chapter 3: Repetition

Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

CS 115 Lecture 8. Selection: the if statement. Neil Moore

COMP 364: Conditional Statements Control Flow

CREATE YOUR CONTENT STRATEGY & LAUNCH PLAN Amanda Genther Inc. & Irresistible Offerings

CS 61A Discussion 8: Scheme. March 23, 2017

Decisions, Decisions. Testing, testing C H A P T E R 7

CS 1110: Introduction to Computing Using Python Loop Invariants

CSE 373: Data Structures and Algorithms. Memory and Locality. Autumn Shrirang (Shri) Mare

CS1 Lecture 3 Jan. 22, 2018

Programming Languages and Techniques (CIS120)

Welcome! COMP s1. Programming Fundamentals

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

At full speed with Python

LOOPS. Repetition using the while statement

Simple Java Programming Constructs 4

Introduction to Python

Introduction to Computer Programming for Non-Majors

EXPRESSIONS, STATEMENTS, AND FUNCTIONS 1

Notebook. March 30, 2019

Python Lists and Dictionaries CS 8: Introduction to Computer Science, Winter 2019 Lecture #13

TUPLES AND RECURSIVE LISTS 5

Python Tutorial. CS/CME/BioE/Biophys/BMI 279 Oct. 17, 2017 Rishi Bedi

Advanced Python. Executive Summary, Session 1

Transcription:

CMSC201 Computer Science I for Majors Lecture 08 Lists

Constants Last Class We Covered More on while loops Sentinel loops Priming Reads Boolean flags 2

Any Questions from Last Time? 3

Today s Objectives To learn about lists and what they are used for To be able to create and update lists To learn different ways to mutate a list To understand the syntax of lists To be able to use the membership in operator To understand how functions and methods differ 4

Reminder About Loop Evaluations The conditional in a while loop is not checked until the body of the loop has finished How many times will this code print Hello? count = 0 while count < 4: count += 1 print("hello") Hello will be printed out four times The loop does NOT stop as soon as count s value is changed to 4 5

Introduction to Lists 6

Exercise: Average Three Numbers Read in three numbers and average them num1 = int(input("please enter a number: ")) num2 = int(input("please enter a number: ")) num3 = int(input("please enter a number: ")) avg = (num1 + num2 + num3) / 3 print(avg) Easy! But what if we want to do 100 numbers? Or 1000 numbers? Do we want to make 1000 variables? 7

Using Lists We need an easy way to hold individual data items without needing to make lots of variables Making num1, num2,..., num99, num100 is time-consuming and impractical Instead, we can use a list to hold our data A list is a data structure: something that holds multiple pieces of data in one structure 8

Lists vs Individual Variables Individual variables are like sticky notes Works best when you only need a few Good for storing different pieces of info Lists are like a checklist written on a single piece of paper Best for storing a lot of related information in one place 9

Properties of a List Heterogeneous (multiple data types!) Contiguous (all together in memory) Ordered (remain in the order they were set in) Have instant ( random ) access to any element Are mutable sequences of arbitrary objects 10

Creating and Modifying Lists 11

Creating an Empty List To create an empty list, use square brackets: newlist = [] This creates a list variable called newlist, with no elements in the list (Sort of like a new checklist on a blank page) Similar to how we create an empty string: newstring = "" 12

List Method: append() The append() method lets us add items to the end of a list, increasing its size Syntax: listname.append( itemtoappend ) Useful for creating a list from flexible input Can start with an empty list, and add items as the user requests them 13

Example of append() We can use append() to create a list of numbers (using a loop to control how many) values = [] # initialize the list to be empty count = 0 # count how many numbers added while count < 4: userval = int(input("enter a number: ")) # add value to the list values.append(userval) count += 1 14

Here s a demonstration of what the code is doing 17 22 5-6 bash-4.1$ python numberlist.py Enter a number: 17 Enter a number: 22 Enter a number: 5 Enter a number: -6 15 values = [] # initialize empty list count = 0 while count < 4: userval = int(input("enter a number: ")) values.append(userval) count += 1

List Method: remove() The remove() method lets us remove an item from the list specifically, it finds and removes the first instance of a given value listname.remove( valuetoremove ) Useful for deleting things we don t need (We won t use it very much in CMSC 201 though) 16

Example of remove() We can use remove() to remove students who have dropped the class from the roster roster = ["Adam", "Ahmed", "Alice", "Andy"] roster = Adam Ahmed Alice Andy 17

Example of remove() We can use remove() to remove students who have dropped the class from the roster roster = ["Adam", "Ahmed", "Alice", "Andy"] roster.remove("adam") # Adam has dropped the class roster = Adam Ahmed Alice Andy 18

Example of remove() We can use remove() to remove students who have dropped the class from the roster roster = ["Adam", "Ahmed", "Alice", "Andy"] roster.remove("adam") # Adam has dropped the class roster.remove("bob") # Bob is not in the roster roster = Ahmed Alice Andy 19

Quick Note Methods vs Functions Functions include things like print() input() int() Methods are a bit different, and include.append().remove() 20

Quick Note Methods vs Functions All you need to know for now is the difference between how they look when written out print("dogs!") names.append("ed") Functions perform the action on the object inside the parentheses This function prints out dogs! Methods perform the action on the object before the period This method appends to names (In this example, it appends Ed ) 21

Editing List Contents 22

Mutating Lists Remember that lists are defined as mutable sequences of arbitrary objects Mutable means we can change them So far, the only thing we ve learned has been how to add or remove items from the list But we can also edit the contents of a list in place, without having to add or remove 23

Using Lists: Individual Variables First, we need an easy way to refer to each individual variable in our list What are some possibilities? Math uses subscripts (x 1, x 2, x 3, etc.) Instructions use numbers ( Step 1: Combine ) Programming languages use a different syntax x[1], x[0], instructions[1], point[i] 24

Accessing Individual Elements Access the individual elements in a list is called indexing into the list Note: List don t start counting from 1 They start counting from 0! 0 1 2 3 4 25

Square Bracket Syntaxes Can use [] to assign initial values mylist = [1, 3, 5] words = ["Hello", "to", "you"] (Also called initialization) 26 And to refer to individual elements of a list >>> print(words[0]) Hello >>> mylist[0] = 4

Length of a List To get a list s length, use the function len() >>> dogs = ["Lacey", "Kieran", "Al"] >>> len(dogs) 3 >>> len([2, 0, 1, 8]) 4 27 Why would we need the length of a list? We ll see in the next few slides!

List Example: Grocery List You are getting ready to head to the grocery store to get some much needed food In order to organize your trip and to reduce the number of impulse buys, you decide to make a grocery list 28

List Example: Grocery List Inputs: 3 items for grocery list Process: Store groceries using list data structure Output: Final grocery list 29

Grocery List Code NUM_GROC = 3 def main(): print("welcome to the Grocery Manager 1.0") grocerylist = [] # initialize empty list # get grocery items from the user count = 0 while count < NUM_GROC: item = input("please enter an item: ") grocerylist.append(item) count += 1 print(grocerylist) main() 30

Grocery List Code MAX_GROC = 3 def main(): print("welcome to the Grocery Manager 1.0") grocerylist = [] # initialize empty list # get grocery items from the user count = 0 while count < MAX_GROC: item = input("please enter an item: ") grocerylist.append(item) count += 1 print(grocerylist) main() 31 Is there a way to do this without using count? How else could we keep track of how long the list is?

Grocery List Code MAX_GROC = 3 def main(): print("welcome to the Grocery Manager 1.0") grocerylist = [] # initialize list # get grocery items from the user while len(grocerylist) < MAX_GROC: item = input("please enter an item: ") grocerylist.append(item) This works just as well as count, but we don t need to keep track of any extra variables! print(grocerylist) main() 32

Iterating Over a List Now that we have our grocery list, how do we iterate over each element of the list and print out its contents? Hint: Use a while loop and the len() function! index = 0 while index < len(grocerylist): print( grocerylist[index]??? ) index += 1 33

Membership in Operator 34

Types of Operators in Python Arithmetic Operators Assignment Operators Comparison Operators Logical Operators Membership Operators Bitwise Operators Identity Operators what we re covering now 35

Membership Operator Example What do you think this code does? hounds = ["Ibizan", "Afghan", "Serbian", "Bassett"] guess = input("please enter a dog: ") while guess not in hounds: print("you guessed wrong!") guess = input("guess again: ") Runs until the user guesses a dog in the list The membership operator can be very useful 36

Membership in Operator Syntax: element in sequence element to look for in keyword may be a list or a string Checks to see if element exists in sequence Evaluates to either True or False Can use it any time you have a conditional Can also use not in to test for absence 37

Time for 38

Livecoding: Updated Grocery List Let s update our grocery list program to allow as many items as the user wants, using a while loop and a sentinel value of STOP Print out the grocery list (item by item) at the end 39 You will need to use: At least one while loop (a sentinel loop) Conditionals A single list

Meta (Remember, either hold down Alt, or hit Esc) 40 Meta + < (Meta + Shift +, ) Moves cursor to the very front/top of the file Meta + > (Meta + Shift +. ) Moves cursor to the very end/bottom of the file

Announcements HW 3 is out on Blackboard now Due by Friday (September 28th) at 8:59:59 PM Next week s lab will be online Midterm October 3rd/4th Review Worksheet out now on course website Out-of-class reviews will happen early next week 41

Image Sources Grocery bag (adapted from): https://www.flickr.com/photos/77106971@n00/1420127033 Sticky note: https://www.flickr.com/photos/winning-information/2325865367 Checklist: https://pixabay.com/p-1316848/ 42