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