lab 3: for and while loops - home | university of pittsburghpitt.edu/~naraehan/ling1330/lab3.pdflab...
TRANSCRIPT
Objectives
Loops
for loop
while loop
Tips
How to program efficiently
Ctrl + c for terminating a process
Indenting and de-indenting a block
1/12/2017 2
Speed-coding fox_in_sox.py
1/12/2017 3
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.
How to program efficiently
1/12/2017 4
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.
How to program efficiently
1/12/2017 5
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.
for x in SEQ : iterates through a sequence (list, str, tuple) for doing
something to each element
Iterates through every element s of the simpsons list and prints the value of s followed by 'is a Simpson.' .
for loop
1/12/2017 6
>>>
>>>
Homer is a Simpson.
Marge is a Simpson.
Bart is a Simpson.
Lisa is a Simpson.
Maggie is a Simpson.
>>>
simpsons = ['Homer', 'Marge', 'Bart', 'Lisa', 'Maggie']
for s in simpsons :
print(s, 'is a Simpson.')
Press ENTER at the end
of each line
for loop over a string
1/12/2017 7
>>> 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
>>>
for l in list('victory') : produces the exact
same result.
In a loop environment, string is interpreted as a sequence of characters
for loop over a list
1/12/2017 8
>>> 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?
Updating value while looping
1/12/2017 9
>>> 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
The final value of total
Add each n to total while looping
for loop over words
1/12/2017 10
>>> 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.
>>>
for loop over words
1/12/2017 11
>>> 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']
Practice
1/12/2017 12
Write a script that takes a sentence from keyboard input, and then prints out:
each word and its length
2 minutes
>>>
================================ RESTART ============
Give me a sentence: Colorless green ideas sleep furiously
Colorless 9
green 5
ideas 5
sleep 5
furiously 9
>>>
1/12/2017 13
# word_length.py
# Demonstrates for loop and summation
sent = input('Give me a sentence: ')
words = sent.split() # tokenize sentence into word list
for w in words : # for every word
print(w, len(w)) # print out word and its length
?
1/12/2017 14
# word_length.py
# Demonstrates for loop and summation
sent = input('Give me a sentence: ')
words = sent.split() # tokenize sentence into word list
for w in words : # for every word
print(w, len(w)) # print out word and its length
Practice
1/12/2017 15
Write a script that takes a sentence from keyboard input, and then prints out:
each word and its length,
the average word length.
2 minutes
>>>
================================ RESTART ============
Give me a sentence: Colorless green ideas sleep furiously
Colorless 9
green 5
ideas 5
sleep 5
furiously 9
The average word length of this sentence is 6.6
>>>
1/12/2017 16
# word_length.py
# Demonstrates for loop and summation
sent = input('Give me a sentence: ')
words = sent.split() # tokenize sentence into word list
total = 0 # total is 0 at first
for w in words : # for every word
print(w, len(w)) # print out word and its length
total += len(w) # add its length to total
# average word length is the total number of characters
# divided by the number of words
avg = total/len(words)
print('The average word length of this sentence is', avg)
2 minutes
1/12/2017 17
# word_length.py
# Demonstrates for loop and summation
sent = input('Give me a sentence: ')
words = sent.split() # tokenize sentence into word list
total = 0 # total is 0 at first
for w in words : # for every word
print(w, len(w)) # print out word and its length
total += len(w) # add its length to total
# average word length is the total number of characters
# divided by the number of words
avg = total/len(words)
print('The average word length of this sentence is', avg)
2 minutes
>>> wd = 'penguin'
>>> new = ''
>>> for x in wd :
new = x + new + x
>>> print(new)
niugneppenguin
for loop to build a new string
1/12/2017 18
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
>>> print(new)
niugnep
>>> wd = 'penguin'
>>> new = ''
>>> for x in wd :
new = x + new + x
>>> print(new)
niugneppenguin
for loop to build a new string
1/12/2017 19
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
>>> print(new)
niugnep
Works as a string-reversing
routine!
while loop
1/12/2017 20
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"
Before
Loop test
Loop body
After
False✘ True✔
while loop: count from 1 to 10
1/12/2017 21
number = 1
while number <= 10 :
␣␣␣␣print(number)
␣␣␣␣number += 1
print('Done!')
number = 1
number <= 10
print(number) number += 1
print('Done!‘)
False✘ True✔
initial condition
tests condition
changes condition
Terminating a process
1/12/2017 22
Aborting a process: Ctrl+c
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.
Guess the secret animal
1/12/2017 23
Let's make it persistent:
keep prompting (loop back !) until correct .
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.')
================================ RESTART
What's the secret animal? fox
Wrong guess. Try again.
>>>
================================ RESTART
What's the secret animal? panda
CORRECT! panda is the secret animal.
>>>
secret.py
1/12/2017 24
================================ 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.
>>>
Guess until correct!
Method 1: which part in loop?
1/12/2017 25
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.
Method 1: which part in loop?
1/12/2017 26
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.
Method 1: while ... ?
1/12/2017 27
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?
?
Method 1: set initial value for g
1/12/2017 28
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
Method 1: try it out
1/12/2017 29
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.')
2 minutes
secret1.py
Copy/download the original script here and edit:
http://www.pitt.edu/~naraehan/ling1330/secret.py
Method 2: using Boolean variable
1/12/2017 30
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.')
secret = 'panda'
correct = False
while not correct :
A new True/False variable which functions as the loop
condition
Method 2: using Boolean variable
1/12/2017 31
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?
Method 2: using Boolean variable
1/12/2017 32
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!
Method 2: try it out
1/12/2017 33
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.')
2 minutes
secret2.py
Summary: method 1
1/12/2017 34
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.')
initial loop condition loop condition test
loop condition-changing operation
secret1.py
Summary: method 2
1/12/2017 35
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
Indenting and de-indenting a block
1/12/2017 36
Select your lines, and then use the commands for changing indentation levels:
Indent Region: Ctrl + ]
Dedent Region: Ctrl + [
Utilizing screen shots
1/12/2017 37
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)
Wrap-up
1/12/2017 38
Next class:
More on Python
Homework 1
Character encoding, palindrome script
Recitation students: work on first script "Naïve Palindrome" before class tomorrow
Need help?
Monday is MLK day: Reed and Na-Rae will be answering emails. Na-Rae *may* be available to meet upon request (email by Sunday).
Friday: Na-Rae available 11:30am – 1pm, 2:20pm – 3 (in 2818 cathedral)