CMSC201 Computer Science I for Majors Lecture 14 – For Loops

Slides:



Advertisements
Similar presentations
CATHERINE AND ANNIE Python: Part 3. Intro to Loops Do you remember in Alice when you could use a loop to make a character perform an action multiple times?
Advertisements

Lists CMSC 201. Overview Today we will learn about: For loops.
CS 206 Introduction to Computer Science II 03 / 06 / 2009 Instructor: Michael Eckmann.
Lecture 13 – range function, for…in loops COMPSCI 1 1 Principles of Programming.
Last Week Doctests Lists List methods Nested Lists Aliasing.
1 09/20/04CS150 Introduction to Computer Science 1 Let ’ s all Repeat Together.
Introduction to Strings Intro to Computer Science CS1510, Section 2 Dr. Sarah Diesburg 1.
All materials copyright UMBC unless otherwise noted CMSC201 Computer Science I for Majors Lecture 02 – Algorithmic Thinking.
CMSC201 Computer Science I for Majors Lecture 19 – Recursion (Continued) Prof. Katherine Gibson Prof. Jeremy Dixon Based on slides from UPenn’s.
Last Class We Covered Decision structures One-way (using if)
CMSC201 Computer Science I for Majors Lecture 08 – Lists
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
String and Lists Dr. José M. Reyes Álamo.
Trace Tables In today’s lesson we will look at:
CMSC201 Computer Science I for Majors Lecture 02 – Algorithmic Thinking Prof. Katherine Gibson Based on slides by Shawn Lupoli and Max Morawski at UMBC.
CMSC201 Computer Science I for Majors Lecture 20 – Recursion (Continued) Prof. Katherine Gibson Based on slides from UPenn’s CIS 110, and from previous.
Topic: Iterative Statements – Part 1 -> for loop
Loops Upsorn Praphamontripong CS 1110 Introduction to Programming
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
CMSC201 Computer Science I for Majors Lecture 17 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 21 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 22 – Searching
Containers and Lists CIS 40 – Introduction to Programming in Python
CMSC201 Computer Science I for Majors Lecture 12 – Lists (cont)
CS1371 Introduction to Computing for Engineers
CS 115 Lecture 8 Structured Programming; for loops
CMSC201 Computer Science I for Majors Lecture 09 – For Loops
Last Class We Covered Dictionaries Hashing Dictionaries vs Lists
Repetition-Counter control Loop
Last Class We Covered The range() function Using for loops
Topics Introduction to Repetition Structures
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Last Class We Covered ASCII values Short circuit evaluation Project 3
CMSC201 Computer Science I for Majors Lecture 10 – Functions (cont)
Structured Programming; for loops Taken from notes by Dr. Neil Moore
CMSC201 Computer Science I for Majors Lecture 15 – For Loops
While Loops BIS1523 – Lecture 12.
Last Class We Covered Dictionaries Hashing Dictionaries vs Lists
CMSC201 Computer Science I for Majors Lecture 16 – Recursion
CMSC201 Computer Science I for Majors Lecture 20 – Dictionaries
Last Class We Covered Data representation Binary numbers ASCII values
CMSC201 Computer Science I for Majors Lecture 07 – While Loops (cont)
Python I/O.
CMSC201 Computer Science I for Majors Lecture 12 – Tuples
CMSC201 Computer Science I for Majors Lecture 19 – Recursion
4. sequence data type Rocky K. C. Chang 16 September 2018
Last Class We Covered Dictionaries Hashing Dictionaries vs Lists
CMSC201 Computer Science I for Majors Lecture 17 – Recursion (cont)
String and Lists Dr. José M. Reyes Álamo.
Remembering lists of values lists
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
CMSC201 Computer Science I for Majors Lecture 08 – For Loops
CMSC201 Computer Science I for Majors Lecture 18 – String Formatting
Last Class We Covered What makes “good code” good Top down design
Let’s all Repeat Together
CMSC201 Computer Science I for Majors Final Exam Information
For loops Taken from notes by Dr. Neil Moore
Last Class We Covered The range() function Using for loops
Loops and Simple Functions
Introduction to Strings
Last Class We Covered Recursion Stacks Parts of a recursive function:
Arrays & Loops.
Arrays & Loops.
Class code for pythonroom.com cchsp2cs
Introduction to Strings
CMSC201 Computer Science I for Majors Lecture 19 – Dictionaries
CMSC201 Computer Science I for Majors Lecture 12 – Program Design
CMPT 120 Lecture 10 – Unit 2 – Cryptography and Encryption –
Presentation transcript:

CMSC201 Computer Science I for Majors Lecture 14 – For Loops

Last Class We Covered Modularity Program design Meaning Benefits Top Down Design Top Down Implementation Bottom Up Implementation #TBT 2 Dimensional lists

Any Questions from Last Time?

Today’s Objectives To learn about the range() function To learn about and be able to use a for loop To understand the syntax of a for loop To be able to combine range() and for To discuss the differences between for loops and while loops

The range() function

Range of Numbers Python has a built-in function called range() that can generate a list of numbers ex = list(range(0, 10)) print(ex) cast it to a list to force it generate the numbers now like slicing – it’s UP TO (but not including) 10 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

range(start, stop, step) Syntax of range() range(start, stop, step) the number we want to start counting at how much we want to count by the number we want to count UP TO (but will not include) the name of the function

Examples of range() There are three ways we can use range() With one number range(10) With two numbers range(10, 20) With three numbers range(10, 20, 2)

range() with One Number If range() is given only one number It will start counting at 0 And will count up to (but not including) that number Incrementing by one list(range(4)) [0, 1, 2, 3]

range() with Two Numbers If we give it two numbers, it will count from the first number up to the second number list(range(5, 10)) list(range(10, 5)) [5, 6, 7, 8, 9] [ ] range() counts up by default!

range() with Two Numbers If we give it two numbers, it will count from the first number up to the second number list(range(-10, -5)) [-10, -9, -8, -7, -6] from a lower to a higher number

range() with Three Numbers If we give it three numbers, it will count from the first number up to the second number, and it will do so in steps of the third number list(range(2, 11, 2)) list(range(3, 28, 5)) [2, 4, 6, 8, 10] [3, 8, 13, 18, 23] range() starts counting at the first number!

Counting Down with range() By default, range() counts up But we can change this behavior If the STEP is set to a negative number, then range() can be used to count down list(range(10, 0, -1)) [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]

for Loops: Iterating over a List

Iterating Through Lists Iteration is when we move through a list, one element at a time Iteration is best completed with a loop We did this previously with our while loop Using a for loop will make our code much faster and easier to write Even faster than the while loop was to write!

for Loops vs while Loops With a while loop, infinite loops are a common problem The programmer is in charge of updating the loop variable, and can easily forget With for loops, infinite loops won’t happen The loop variable is updated by Python It’s handled “for” you!

Using range() in for Loops We can use the range() function to control a loop through “counting” for i in range(0, 20): print(i + 1) What will this code do? Print the numbers 1 through 20 on separate lines The for loop is iterating over the numbers

Using range() in for Loops When we use the range() function in for loops, we don’t need to cast it to a list The for loop handles that for us print("Counting by fives...") for num in range(5, 26, 5): print(num) 5 10 15 20 25 call the range() function, but don’t need to cast it to a list

Using for Loops with Lists

Using a for Loop with Lists We can combine a simple for loop with a list and the range() function, as shown below for i in range( len(theList) ): print( theList[i] ) What’s the benefit to doing it this way? Why do we need range() and len()? We’ll answer these questions momentarily

Breaking It All Down If theList has a length of 8, what list does the range() in the for loop generate? for i in range( len(theList) ): print( theList[i] ) It will generate a list [0,1,2,3,4,5,6,7] What does this represent? The indexes of the list theList

Why range() and len()? Why do we need len()? Why do we need range()? To know how many indexes the list has It will give us an integer value Why do we need range()? To generate all the indexes of the list What does range() do with one number? Start at 0, and count up to the number given

Common Error Pay attention with len() and range() Which goes on the outside? range() It needs the length to generate the indexes If you use them backwards: TypeError: 'list' object cannot be interpreted as an integer

Time for… LIVECODING!!!

Running a Kennel You are running a kennel with space for 5 dogs You ask your 3 assistants to do the following, using the list of dogs in your office: Tell you all of the dogs in the kennel Tell you what pen number each dog is in Later, all the dogs have been picked up, and someone dropped off their 5 German Shepherds, so the list in your office needs to be updated

Running a Kennel The dogs in your kennel at the start are: Alaskan Klee Kai Beagle Chow Chow Doberman English Bulldog

Kennel Sample Output Assistant #1: Alaskan Klee Kai Beagle Chow Chow Doberman English Bulldog Assistant #2: There is a Alaskan Klee Kai in kennel pen 0 There is a Beagle in kennel pen 1 There is a Chow Chow in kennel pen 2 There is a Doberman in kennel pen 3 There is a English Bulldog in kennel pen 4 Assistant #3: At the end of the day: German Shepherd

Using Loops to Make 2D Lists The easiest way to create a 2D list is to ...? Start with an empty one-dimensional list Create the first “row” as a separate list Append it to the original 1D list Repeat until all rows are added to the list You can use a while loop, but for loops are great at creating lists of a specific size

Example: Creating 2D List Create a 6-high by 4-wide list of underscores board = [] row = [] for i in range(4): row.append("_") for i in range(6): board.append( row[:] ) why is this here? each row needs to be individual, hence it needs to be deep copied

Example: Creating 2D List from Input Create a list of names and majors for 5 students info = [] for i in range(5): name = input("Enter name: ") major = input("Major? ") row = [name, major] info.append(row) why doesn’t this row need to be deep copied?

Daily CS History Grace Hopper Popularized the term “computer bug” Invented the COBOL language Invented one of the first compilers US Navy Rear Admiral Retired at the age of 79

Announcement: Advising CMSC and CMPE students, sign up for an advising appointment. http://advising.coeit.umbc.edu/registration/ Select that you are in MATH 150 or higher and haven't completed the gateway. There are both group advising and individual advising appointments open. The earliest dates available are for group advising.

Announcements Project 2 is out on Blackboard now Design is due by Friday (Nov 3rd) at 8:59:59 PM Design is entirely up to you, so think about it carefully! Project is due by Friday (Nov 10th) at 8:59:59 PM Final exam is Friday, December 15th from 6 to 8 PM

Image Sources Rollercoaster: Dog images: Grace Hopper (adapted from): https://commons.wikimedia.org/wiki/File:Corkscrew_(Cedar_Point)_01.jpg Dog images: https://commons.wikimedia.org/wiki/File:WOWAKK-Kukai-Alaskan-Klee-Kai.jpg https://commons.wikimedia.org/wiki/File:Cute_beagle_puppy_lilly.jpg https://commons.wikimedia.org/wiki/File:01_Chow_Chow.jpg https://commons.wikimedia.org/wiki/File:Dobermannwurf.jpg https://commons.wikimedia.org/wiki/File:English_Bulldog_puppy.jpg Grace Hopper (adapted from): https://en.wikipedia.org/wiki/File:Commodore_Grace_M._Hopper,_USN_(covered).jpg