Lab 3: for and while Loops, Indexing. Ling 1330/2330: Computational Linguistics Na-Rae Han

Similar documents
Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Lab 6: Data Types, Mutability, Sorting. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 8: File I/O, Mutability vs. Assignment. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han

Lab 2: input(), if else, String Operations, Variable Assignment. Ling 1330/2330: Computational Linguistics Na-Rae Han

Lab 1: Course Intro, Getting Started with Python IDLE. Ling 1330/2330 Computational Linguistics Na-Rae Han

Programming Fundamentals and Python

Lab 18: Regular Expressions in Python. Ling 1330/2330: Intro to Computational Linguistics Na-Rae Han

Lab 20: Regular Expressions in Python. Ling 1330/2330: Computational Linguistics Na-Rae Han

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

The second statement selects character number 1 from and assigns it to.

Lab 7: Reading Files, Importing, Bigram Function. Ling 1330/2330: Computational Linguistics Na-Rae Han

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Some material adapted from Upenn cmpe391 slides and other sources

Hello World! Computer Programming for Kids and Other Beginners. Chapter 1. by Warren Sande and Carter Sande. Copyright 2009 Manning Publications

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

COMP 204: Sets, Commenting & Exceptions

Python Programming Exercises 3

Compound Data Types 1

Ch.2: Loops and lists

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

Programming for Engineers in Python. Autumn

Accelerating Information Technology Innovation

Programming for Engineers in Python. Recitation 1

18.1. CS 102 Unit 18. Python. Mark Redekopp

Lists, loops and decisions

Introduction to Python

CMSC201 Computer Science I for Majors

Introduction to Python

CPD for GCSE Computing: Practical Sheet 6 February 14

In addition to numbers and strings, Python also lets us represent lists of things (just like in AppInventor).

COMP1730/COMP6730 Programming for Scientists. Strings

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Not-So-Mini-Lecture 6. Modules & Scripts

Accelerating Information Technology Innovation

Errors. And How to Handle Them

Lists How lists are like strings

LING 510, Lab 3 September 23, 2013

Data Structures. Lists, Tuples, Sets, Dictionaries

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

Unit 7. 'while' Loops

Scripting Languages. Python basics

MEIN 50010: Python Flow Control

Professor: Sana Odeh Lecture 3 Python 3.1 Variables, Primitive Data Types & arithmetic operators

An introduction to Python

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Python Intro GIS Week 1. Jake K. Carr

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

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

Collections. Lists, Tuples, Sets, Dictionaries

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

Types, lists & functions

Working with Sequences: Section 8.1 and 8.2. Bonita Sharif

Shell Programming (Part 2)

St. Benedict s High School. Computing Science. Software Design & Development. (Part 1 Computer Programming) National 5

Introduction to Python

To add something to the end of a list, we can use the append function:

3 The Building Blocks: Data Types, Literals, and Variables

The current topic: Python. Announcements. Python. Python

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

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

Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10

Exercise: The basics - variables and types

COMP 204: Sets, Commenting & Exceptions

CS1 Lecture 3 Jan. 22, 2018

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

Python for Non-programmers

How Do Robots Find Their Way?

Python language: Basics

Introduction to String Manipulation

MUTABLE LISTS AND DICTIONARIES 4

PYTHON TRAINING COURSE CONTENT

Beyond Blocks: Python Session #1

CS 302: INTRODUCTION TO PROGRAMMING. Lectures 7&8

Part III Appendices 165

Introductory Linux Course. Python I. Martin Dahlö UPPMAX. Author: Nina Fischer. Dept. for Cell and Molecular Biology, Uppsala University

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

Unit 7: Algorithms and Python CS 101, Fall 2018

Python: common syntax

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

CSCI 121: Anatomy of a Python Script

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

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

CE151 ASSIGNMENT

Computer and Programming: Lab 1

CMSC 201 Computer Science I for Majors

An Introduction to Python

Algorithms and Programming I. Lecture#12 Spring 2015

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

MEIN 50010: Python Strings

Girls Programming Network. Markov Chains Workbook 1

Lecture 4. while and for loops if else test Tuples Functions. Let us start Python Ssh (putty) to UNIX/Linux computer puccini.che.pitt.

Shell / Python Tutorial. CS279 Autumn 2017 Rishi Bedi

Comp 151. Control structures.

Announcements For This Lecture

Python is available at: Why Python is awesome:

Introduction to Python (All the Basic Stuff)

Programming in Python

Level 3 Computing Year 2 Lecturer: Phil Smith

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Transcription:

Lab 3: for and while Loops, Indexing Ling 1330/2330: Computational Linguistics Na-Rae Han

Objectives Split vs. join Loops for loop while loop Indexing List and string indexing & slicing Tips How to program efficiently, aka "Code in shell" Ctrl + c for terminating a process Indenting and de-indenting a block 9/4/2018 2

Speed-coding fox_in_sox.py Video of me completing the script, in 5x speed! http://www.pitt.edu/~naraehan/ling1330/code_in_shell.mp4 Watch closely! This may well be the most important video yet It will change your life. 9/4/2018 3

How to program efficiently The rookie way: You are doing all your coding in the script window, blindly. You only use the IDLE shell to verify the output of your script. 9/4/2018 4

How to program efficiently The seasoned Python programmer way: After a script is run, all the variables and the objects in it are still available in IDLE shell for you to tinker with. Experimenting in SHELL is much quicker instant feedback! You should go back and forth between SCRIPT and SHELL windows, successively building up your script. 9/4/2018 5

.join() operation How do you turn a list into a string?.join() kids = ['Bart', 'Lisa', 'Nelson', 'Milhouse'] '-'.join(kids) 'Bart-Lisa-Nelson-Milhouse' ' and '.join(kids) 'Bart and Lisa and Nelson and Milhouse' creatures = ['man', 'bear', 'pig'] ''.join(creatures) 'manbearpig' Joins on an empty string ('') 9/4/2018 6

.join() syntax How do you turn a list into a string?.join() kids = ['Bart', 'Lisa', 'Nelson', 'Milhouse'] '-'.join(kids) 'Bart-Lisa-Nelson-Milhouse' Note the syntax!.join() method is called on the "joiner" string and not the list "joiner" string List to be joined 9/4/2018 7

Using.split() and.join() Split a phrase/sentence (string) into words (list), and then join them back with a space mary = 'Mary had a little lamb' mwords = mary.split() mwords ['Mary', 'had', 'a', 'little', 'lamb'] ' '.join(mwords) 'Mary had a little lamb' List-ify a word (string) into characters (list), and then join them back with an empty string '' v = 'victory' list(v) ['v', 'i', 'c', 't', 'o', 'r', 'y'] ''.join(list(v)) 'victory' Splitting on empty string '' v.split('') does NOT work! 9/4/2018 8

Try it out 1 minute Split a phrase/sentence (string) into words (list), and then join them back with a space mary = 'Mary had a little lamb' mwords = mary.split() mwords ['Mary', 'had', 'a', 'little', 'lamb'] ' '.join(mwords) 'Mary had a little lamb' List-ify a word (string) into characters (list), and then join them back with an empty string '' v = 'victory' list(v) ['v', 'i', 'c', 't', 'o', 'r', 'y'] ''.join(list(v)) 'victory' 9/4/2018 9

for loop for x in SEQ : iterates through a sequence (list, str, tuple) for doing something to each element simpsons = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie'] for s in simpsons : print(s, 'is a Simpson.') Press ENTER at the end of each line Homer is a Simpson. Marge is a Simpson. Bart is a Simpson. Lisa is a Simpson. Maggie is a Simpson. Iterates through every element s of the simpsons list and prints the value of s followed by 'is a Simpson.'. 9/4/2018 10

for loop over a string for l in 'victory' : print('give me a', l) Give me a v Give me a i Give me a c Give me a t Give me a o Give me a r Give me a y In a loop environment, string is interpreted as a sequence of characters for l in list('victory') : produces the exact same result. 9/4/2018 11

for loop over a list for n in [75, 80, 95, 55, 80]: print(n) 75 80 95 55 80 Looping though a list of numbers How to calculate a total? 9/4/2018 12

Updating value while looping total = 0 for n in [75, 80, 95, 55, 80]: total += n print(n, 'Total is now', total) 75 Total is now 75 80 Total is now 155 95 Total is now 250 55 Total is now 305 80 Total is now 385 total 385 New variable created with initial value of 0 Add each n to total while looping The final value of total *You can also use sum() 9/4/2018 13

for loop over words chom = 'Colorless green ideas sleep furiously' for w in chom.split() : print('"'+w+'"', 'is', len(w), 'characters long.') "Colorless" is 9 characters long. "green" is 5 characters long. "ideas" is 5 characters long. "sleep" is 5 characters long. "furiously" is 9 characters long. 9/4/2018 14

for loop over words chom = 'Colorless green ideas sleep furiously' for w in chom.split() : print('"'+w+'"', 'is', len(w), 'characters long.') "Colorless" is 9 characters long. "green" is 5 characters long. "ideas" is 5 characters long. "sleep" is 5 characters long. "furiously" is 9 characters long. chom string must be first turned into a list of words through.split() chom.split() ['Colorless', 'green', 'ideas', 'sleep', 'furiously'] How to calculate the average word length? 9/4/2018 15

Average word length chom = 'Colorless green ideas sleep furiously' total = 0 for w in chom.split() : print('"'+w+'"', 'is', len(w), 'characters long.') total += len(w) "Colorless" is 9 characters long. "green" is 5 characters long. "ideas" is 5 characters long. "sleep" is 5 characters long. "furiously" is 9 characters long. total 33 total / len(chom.split()) 6.6 9/4/2018 16

for loop to build a new string 2 minutes wd = 'penguin' new = '' for x in wd : new = new + x + x print(new) ppeenngguuiinn wd = 'penguin' new = '' for x in wd : new = x + new + x print(new) niugneppenguin wd = 'penguin' new = '' for x in wd : new = x + new print(new) niugnep 9/4/2018 17

for loop to build a new string 2 minutes wd = 'penguin' new = '' for x in wd : new = new + x + x print(new) ppeenngguuiinn wd = 'penguin' new = '' for x in wd : new = x + new + x print(new) niugneppenguin wd = 'penguin' new = '' for x in wd : new = x + new print(new) niugnep Works as a string-reversing routine! 9/4/2018 18

while loop Before Loop test False True Loop body We need a looping mechanism that keeps going until a certain condition holds: "Keep counting until 10" "Keep adding 5 as long as the sum is less than 100" "Keep trying until you have the correct answer" After 9/4/2018 19

while loop: count from 1 to 10 number = 1 number = 1 initial condition number <= 10 False True print(number) number += 1 while number <= 10 : print(number) number += 1 tests condition print('done! ) print('done!') changes condition 9/4/2018 20

Terminating a process Aborting a process: Ctrl+c 1 minute Try this in IDLE shell: Bad things can happen when you forget to include a condition-changing operation in the while loop. Ctrl+c when things go haywire. 9/4/2018 21

Guess the secret animal secret = 'panda' g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') secret.py ================================ RESTART What's the secret animal? fox Wrong guess. Try again. ================================ RESTART What's the secret animal? panda CORRECT! panda is the secret animal. Let's make it persistent: keep prompting (loop back!) until correct. 9/4/2018 22

Guess until correct! ================================ RESTART What's the secret animal? fox Wrong guess. Try again. What's the secret animal? dog Wrong guess. Try again. What's the secret animal? cat Wrong guess. Try again. What's the secret animal? panda CORRECT! panda is the secret animal. 9/4/2018 23

Method 1: which part in loop? secret = 'panda' g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 9/4/2018 24

Method 1: which part in loop? secret = 'panda' g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 9/4/2018 25

Method 1: while...? secret = 'panda' while g!=? secret : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 3. What's the condition for looping back? 9/4/2018 26

Method 1: set initial value for g secret = 'panda' g = '' while g!= secret : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 1. Figure out which part should be repeated. 2. Put the part in the while loop block. 3. What's the condition for looping back? 4. Before looping begins, the initial value of g must be set 9/4/2018 27

Method 2: using Boolean variable secret = 'panda' g correct = '' = False while g not!= correct secret : g = input("what's the secret animal? ") A new True/False variable which functions as the loop condition if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') 9/4/2018 28

Method 2: using Boolean variable secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') But there's something wrong here. What is it? 9/4/2018 29

Method 2: using Boolean variable secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') correct = True else : print('wrong guess. Try again.') Variable value must be explicitly set to True in loop body. Otherwise the loop will never terminate! 9/4/2018 30

Method 2: try it out 2 minutes secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') correct = True else : print('wrong guess. Try again.') secret2.py Copy/download the original script here and edit: http://www.pitt.edu/~naraehan/ling1330/secret.py 9/4/2018 31

Indenting and de-indenting a block Select your lines, and then use the commands for changing indentation levels: Indent Region: Ctrl + ] Dedent Region: Ctrl + [ Beware of TAB vs. SPACE mismatch! (If you are copy-pasting) 9/4/2018 32

Summary: method 1 secret = 'panda' g = '' while g!= secret : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') else : print('wrong guess. Try again.') secret1.py initial loop condition loop condition test loop condition-changing operation 9/4/2018 33

Summary: method 2 secret = 'panda' correct = False while not correct : g = input("what's the secret animal? ") if g == secret : print('correct!', secret, 'is the secret animal.') correct = True else : print('wrong guess. Try again.') initial loop condition loop condition test loop condition-changing operation secret2.py 9/4/2018 34

Indexing Individual items of a string, list, or tuple can be accessed using square bracket "array" notation: [index] Index starts from 0! 'e' 2 'Marge' st = 'Hello, world!' st[1] li = [1, 2, 'ab', 3.14] li[1] tu = ('Homer', 'Marge', 'Bart', 'Lisa') tu[1] 9/4/2018 35

Positive vs. negative indices st = 'Hello!' li = ['Mary', 'had', 'a', 'little', 'lamb'] Positive index: count from the left, starting with 0 st[1] 'e' li[1] 'had' Negative index: count from right, starting with -1 st[-1] '!' li[-1] 'lamb' H e l l o! 0 1 2 3 4 5-6 -5-4 -3-2 -1 9/4/2018 36

Slicing returns a copy of a subset Slicing syntax: s[start:end] Returns the elements beginning at start and extending up to but not including end Copying starts at the first index, and stops copying before the second index! 'ell' st = 'Hello!' st[1:4] li[2:4] ['ab', 3.14] li = [1, 2, 'ab', 3.14, 'c'] You can also use negative indices when slicing: st[1:-1] 'ello' li[1:-2] [2, 'ab'] 9/4/2018 37

Slicing st = 'Hello!' li = [1, 2, 'ab', 3.14, 'c'] Omit the first index [:5] to make a copy starting from the beginning: st[:4] 'Hell' li[:3] [1, 2, 'ab'] Omit the second index [2:] to make a copy till the end: st[1:] 'ello!' li[-3:] ['ab', 3.14, 'c'] 9/4/2018 38

String indexing/slicing examples 'a' 'e' 'e' 'an' 'ora' w = 'orange' w[2] w[5] w[6] Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> w[6] IndexError: string index out of range w[-1] w[2:4] w[0:3] w[2:] 'ange' w[-2:] 'ge' o r a n g e 0 1 2 3 4 5-6 -5-4 -3-2 -1 w[:4] 'oran' w[:-1] 'orang' w[2:100] 'ange' w[:2] + w[2:] 'orange' w[:3] + w[3:] 'orange' w[:] 'orange' w[4:4] '' 39

List indexing/slicing examples 30 li = [10, 20, 30, 40, 50] li[2] li[5] Traceback (most recent call last): File "<pyshell#17>", line 1, in <module> li[5] IndexError: list index out of range li[-3] 30 li[2:4] [30, 40] li[:4] [10, 20, 30, 40] li[3:] [40, 50] li[2:3] [30] li[2:2] [] li[:3] + li[3:] [10, 20, 30, 40, 50] li[:] [10, 20, 30, 40, 50] Not 30! 9/4/2018 40

What makes Apple product names? Apple products: iphone ipad imessage itunes iwatch NOT: eprime McAfee ihop IMAX iamyourfather First character is 'i' Second character is uppercase The rest are lowercase 9/4/2018 41

Practice: Apple product? 2 minutes Write a script that: prompts for a string input prints YES/NO for being an Apple product name name = input('give me an Apple name: ') if name[0] == 'i' and name[1].isupper() and name[2:].islower() : print('yes!') else : print('no.') apple.py ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: iphone NO. ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: imessage YES! Use these functions: 'abc'.islower() True 'AB'.isupper() True 9/4/2018 42

Practice: Apple product? 2 minutes Write a script that: prompts for a string input prints YES/NO for being an Apple product name name = input('give me an Apple name: ') if name[0] == 'i' and name[1].isupper() and name[2:].islower() : print('yes!') else : print('no.') apple.py ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: iphone NO. ============ RESTART: C:/Users/ /apple.py ==== Give me an Apple name: imessage YES! Use these functions: 'abc'.islower() True 'AB'.isupper() True 9/4/2018 43

Utilizing screen shots Screen shots are handy. Good for note taking and asking questions. Win/OS-X native solutions: http://www.pitt.edu/~naraehan/python3/faq.html#q-screen-shot Third-party applications: Greenshot (Windows only) http://getgreenshot.org/ Jing (Windows & Mac) https://www.techsmith.com/jing.html They offer added convenience: annotate screenshots, video screencasts (Jing) 9/4/2018 44

Wrap-up Next class: Lab: more on Python Lecture: Character encoding (Lang & Computer ch.1) Exercise 3 Palindrome script in 3 stages: naive, smart, insistent We will send you ANSWER KEY for first 2. Follow instructions: START EARLY!! Plenty of office hours tomorrow. 9/4/2018 45