Week 3: Loops and strings

Slides:



Advertisements
Similar presentations
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Advertisements

James Tam Loops In Python In this section of notes you will learn how to rerun parts of your program without having to duplicate the code.
Chapter 4: Looping CSCI-UA 0002 – Introduction to Computer Programming Mr. Joel Kemp.
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Fundamentals of Python: First Programs
THE BIG PICTURE. How does JavaScript interact with the browser?
Chapter 2 - Algorithms and Design
If statements while loop for loop
An Introduction to Programming with C++ Sixth Edition Chapter 7 The Repetition Structure.
Control Structures II Repetition (Loops). Why Is Repetition Needed? How can you solve the following problem: What is the sum of all the numbers from 1.
Xin Liu Feb 4, * Use midterm questions for previous 231/217 midterms for practices * ams
Programming Logic and Design Fourth Edition, Comprehensive Chapter 8 Arrays.
Control Structures RepetitionorIterationorLooping Part I.
Conditional Loops CSIS 1595: Fundamentals of Programming and Problem Solving 1.
Last Week Modules Save functions to a file, e.g., filename.py The file filename.py is a module We can use the functions in filename.py by importing it.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Chapter 10 Loops: while and for CSC1310 Fall 2009.
Midterm Exam Topics (Prof. Chang's section) CMSC 201.
Loops and Iteration Chapter 5 Python for Informatics: Exploring Information
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
While loops. Iteration We’ve seen many places where repetition is necessary in a problem. We’ve been using the for loop for that purpose For loops are.
Python Simple file reading Peter Wad Sackett. 2DTU Systems Biology, Technical University of Denmark Simple Pythonic file reading Python has a special.
CSC 108H: Introduction to Computer Programming Summer 2012 Marek Janicki.
CMSC201 Computer Science I for Majors Lecture 08 – Lists
Python Basics.
CMSC201 Computer Science I for Majors Lecture 07 – While Loops
String and Lists Dr. José M. Reyes Álamo.
Discussion 4 eecs 183 Hannah Westra.
Topic 4: Looping Statements
Topic: Iterative Statements – Part 1 -> for loop
Chapter 5: Control Structures II (Repetition)
Topics Introduction to Repetition Structures
Loops and Iteration Chapter 5 Python for Everybody
Python: Control Structures
Lesson 05: Iterations Class Chat: Attendance: Participation
Warm-up Program Use the same method as your first fortune cookie project and write a program that reads in a string from the user and, at random, will.
Think What will be the output?
Programming 101 Programming for non-programmers.
Week 5: Dictionaries and tuples
Week 4: Files and lists Python workshop Week 4: Files and lists
Week 3: Loops and strings
Repetition-Sentinel,Flag Loop/Do_While
While Loops in Python.
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.
CHAPTER 7 STRINGS.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
While loops The while loop executes the statement over and over as long as the boolean expression is true. The expression is evaluated first, so the statement.
Iteration with While You can say that again.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Lesson 05: Iterations Topic: Introduction to Programming, Zybook Ch 4, P4E Ch 5. Slides on website.
Python - Strings.
Introduction to Object-Oriented Programming with Java--Wu
4. sequence data type Rocky K. C. Chang 16 September 2018
IST256 : Applications Programming for Information Systems
String and Lists Dr. José M. Reyes Álamo.
CMSC201 Computer Science I for Majors Lecture 09 – While Loops
CMSC201 Computer Science I for Majors Lecture 08 – For Loops
Python programming exercise
CSC115 Introduction to Computer Programming
CHAPTER 6: Control Flow Tools (for and while loops)
Introduction to Computer Science
Another Example Problem
While Loops in Python.
Topic: Iterative Statements – Part 2 -> for loop
CMPT 120 Lecture 13 – Unit 2 – Cryptography and Encryption –
Iteration – While Loops
Presentation transcript:

Week 3: Loops and strings barbera@van-schaik.org Python workshop Week 3: Loops and strings 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: Files and lists Week 5: Dictionaries and tuples Acknowledgments: Structure of the workshop follows the book “Python for informatics” by Charles Severance. Several examples are from this book or the accompanying slides.

https://s-media-cache-ak0. pinimg https://s-media-cache-ak0.pinimg.com/originals/d9/8c/e7/d98ce7fa25410cc283eb9feb4343f86c.jpg Loops

99 bottles of beer https://en.wikipedia.org/wiki/Beer 99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall... 98 bottles of beer on the wall, 98 bottles of beer. Take one down, pass it around, 97 bottles of beer on the wall... . No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall... Try this script and fix the error: bottles-of-beer-contains-error.py https://en.wikipedia.org/wiki/Beer You can refine this script to deal with the case of 1 bottle of beer

99 bottles of beer n = 99 while n>0: if n > 0: print(n, "bottles of beer on the wall,", n ,"bottles of beer.") n = n - 1 print("Take one down, pass it around,", n, "bottles of beer on the wall...\n") if n == 0: print("No more bottles of beer on the wall, no more bottles of beer.") print("Go to the store and buy some more, 99 bottles of beer on the wall...\n")

Declaration of a variable >>> x = x + 1 You can't use/update a variable that doesn't exist yet >>> x = 0 Declaration of X http://www.gograph.com/vector-clip-art/scroll-shapes.html

What happens in a loop? Evaluate the condition, True or False If the condition is false, exit the while statement and continue execution at the next statement If the condition is true, execute the body and then go back to step 1 http://science.howstuffworks.com/engineering/structural/roller-coaster7.htm

∞ Infinite loops Try: bottles-of-beer-infinite-loop.py With CTRL+C you can stop the program Then try: bottles-of-beer-contains-error.py

∞ Infinite loops You need to make sure that the loop can end n = 99 while n>=0: if n > 0: print(n, "bottles of beer on the wall,", n ,"bottles of beer.") n = n - 1 print("Take one down, pass it around,", n, "bottles of beer on the wall...\n") if n == 0: print("No more bottles of beer on the wall, no more bottles of beer.") print("Go to the store and buy some more, 99 bottles of beer on the wall...\n") You need to make sure that the loop can end

Type of errors Syntax error (typos, forgetting closing quotes) Python will give an error Logic error seconds = hours / 3600 average = a + b / 2 Off-by-one error https://en.wikipedia.org/wiki/Off-by-one_error Off-by-one or fence-post error

Useful infinite loops while True: line = input("Say 'when'> ") Let a sensor measure the temperature endlessly Ask user for input until an answer is correct while True: line = input("Say 'when'> ") if line == 'when': break print(line) print('Done!') say-when.py

continue and break while True: line = input('> ') if line[0] == '#' : continue if line == 'done': break print(line) print('Done!') Example from the book continue-and-break.py

for loops applepie.py snoepjes.py groceries = ["apples", "flour", "butter", "eggs", "sugar"] for item in groceries: print("Don't forget the", item) snoepjes.py for i in range(10): print(i, "Ik mag niet met snoepjes gooien")

Count stuff total = 0 for i in [32, 45, 8, 10, 25]: total = total + i print("Total:", total) Example from book count-stuff.py

Maximum largest = None print('Before:', largest) for itervar in [3, 41, 12, 9, 74, 15]: if largest is None or itervar > largest : largest = itervar print('Loop:', itervar, largest) print('Largest:', largest) Example from book get-maximum.py

Wrap-up A loop usually has the following A variable is declared (counter or something finite) Evaluation (conditional) of variable to end the loop Something is done in the loop http://www.zazzle.com/snake+pattern+wrappingpaper

Strings http://www.roylco.com/product/R2184/language/2/Manuscript_Letter_Beads

Strings A string is a sequence >>> fruit = “banana” >>> letter = fruit[1] https://en.wikipedia.org/wiki/Banana b a n 1 2 3 4 5

Length and indices Length >>> len(fruit) Get the last index >>> last = fruit[length] >>> last = fruit[length-1] Get the last letter >>> fruit[-1] https://en.wikipedia.org/wiki/Banana

Letter by letter: while loop index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 https://en.wikipedia.org/wiki/Fruit

Letter by letter: for loop for letter in fruit: print(letter) https://en.wikipedia.org/wiki/Fruit

Slices >>> s = “banana” >>> s[0:3] # ban >>> s[3:] # ana >>> s[3:3] # '' >>> s[2:5] # nan >>> s[:] # banana http://www.freeimages.com/search/cartoon-banana

Mutability >>> x = "cookies" This will give an error: >>> x[0] = “b” Solution, use slices: >>> new = x[:3] + "l" >>> print(new) http://www.thegreatcookie.com/collections/cookies

Count letters Write a program that counts all the a's in 'banana' Hint for loop a variable to count if statement to check if the letter is an a

“in” and string comparison Check if letter or substring is in a string >>> 'a' in 'banana' >>> 'ana' in 'banana' Comparisons >>> 'mouse' == 'mouse' >>> 'Mouse' == 'mouse' >>> 'elephant' > 'cow' >>> 'dinosaur' < 'cat' >>> 'mouse' > 'Zebra' https://en.wikipedia.org/wiki/Zoo

String methods upper() / lower() find() startswith() strip() How to use this: >>> s = 'cow' >>> s.upper() >>> type(s) >>> dir(s) >>> help(str.upper) https://en.wikipedia.org/wiki/Cattle

Parsing strings >>> s = ' From: Barbera <barbera@van-schaik.org>' >>> s.find("@") 23 >>> start = s.find("<") >>> end = s.find(">") >>> s[start:end] '<barbera@van-schaik.org' >>> s[start+1:end] 'barbera@van-schaik.org' http://prajwaldesai.com/create-user-mailbox-in-exchange-server-2013/

More Chapter 6 Format operator Documentation string methods https://docs.python.org/3/library/string.html

Assignment – guessing game Write a program that generates a random number between 1 and 10 Let the user guess which number the computer had in mind The user can guess at most 5 times Give hints “higher” and “lower” when the guessed number is too high or too low Partial code is available on the wiki guess-game.py

Next week Next: Files and lists More programming exercise? Chapter 5 and 6 of the book Tot volgende week!!