Coding with Counting Songs: “Ten Green Bottles” in Python
-
Upload
steven-battle -
Category
Education
-
view
802 -
download
0
Transcript of Coding with Counting Songs: “Ten Green Bottles” in Python
Coding with Counting Songs: “Ten Green Bottles”
in PythonSteve Battle
counting songs• A repeated verse, each time with one bottle fewer:
Ten green bottles hanging on the wallTen green bottles hanging on the wallAnd if one green bottle should accidentally fall,There'll be nine green bottles hanging on the wall.
• Continue until the number of bottles reaches zero:One green bottle hanging on the wall,One green bottle hanging on the wall,And if that green bottle should accidentally fall,There'll be no more bottles hanging on the wall.
• See https://en.wikipedia.org/wiki/Ten_Green_Bottles
IDLE* and the REPL**Start IDLE, the Python Development Environment.Type:>>> print(“Ten green bottles”)
* Integrated DeveLopment Environment** Read, Evaluate, Print, Loop
programs and strings• In IDLE, create a new file for our code:File > New File
• Input the following code:print(“Ten green bottles, hanging on the wall”)
• Always save your file before running it:File > Save (Save As: bottles.py)
• Now Run your code:Run > Run Module (F5)
sequenceA program can have a sequence of statements that are executed in order:
print("Ten green bottles, hanging on the wall")print("Ten green bottles, hanging on the wall")
The output is simply:Ten green bottles, hanging on the wallTen green bottles, hanging on the wall
variablesA variable is like a named box you can put a value into and use later:
bottles = 10print(bottles," green bottles, hanging on the wall")print(bottles," green bottles, hanging on the wall”)
If you’re using Python 2.7 you may have to use:
print str(bottles)+” green bottles, hanging on the wall”
• Variables in Python are untyped.
expressions• Math expressions use the operators: + (plus), - (minus), * (times), / (divide), % (quotient)
• Add the following code to the end of your program:print("And if one green bottle should accidentally fall,")print("There'll be”, bottles-1, "green bottles, hanging on the wall.”)
• The multiplicative operators (* / %) have higher precedence and are evaluated before the additive operators (+ -)
• Use brackets () to change the order of evaluation
loopsWe want to repeat the verse 10 times
• The ‘for’ loop defines a loop variable and loops (iterates) over a range of values
Enter the following in the REPL, what happens?>>> for i in range(10):
print(i)>>> for i in range(1,10): print(i)
Modify your program, indenting the body of the loop:
for bottles in range(10,0,-1): print(bottles,"green bottles, hanging on the wall,") print(bottles,"green bottles, hanging on the wall,") print("And if one green bottle should accidentally fall..") print("There'll be”, bottles-1,
"green bottles, hanging on the wall.\n")
functionsFunctions let us isolate reusable code, like the “green bottles” statement.
def greenBottles(b): print(b,"green bottles, hanging on the wall,")
for bottles in range(10,0,-1): greenBottles(bottles) greenBottles(bottles) print("And if one green bottle should accidentally fall..") print("There'll be”, bottles-1,"green bottles, hanging on the wall.\n")
• The scope of ‘b’ is limited to the function
return valuesProper functions return a value. This lets us reuse the function on the last line of the verse.
• In this case it returns a string value that is printed def greenBottles(b): return str(b)+" green bottles, hanging on the wall"
for bottles in range(10,0,-1): print(greenBottles(bottles)) print(greenBottles(bottles)) print("And if one green bottle should accidentally fall..") print("There'll be ", greenBottles(bottles-1)) print()
conditionalsHow do we handle variation in the verse such as the plurality of the bottles?
• An ‘if’ statement lets the code select alternatives depending upon some condition.
• The condition here is b==1 (b ‘equals’ 1)def greenBottles(b): if b==1: return str(b)+" green bottle, hanging on the wall" else: return str(b)+" green bottles, hanging on the wall”
And modify the “There’ll be” line to: print("There'll be ", greenBottles(bottles-1))
conditional expressionsWhat about “one green bottle” changing to “that green bottle” in the last verse?
• Conditional expressions return a value and are sometimes a more compact alternative.
for bottles in range(10,0,-1):print(greenBottles(bottles))print(greenBottles(bottles))print("And if " + ("that" if bottles==1 else "one")+ " green bottle should accidentally fall.”)
print("There'll be ", greenBottles(bottles-1)print()
data structuresWe want to use written numerals, “ten”, “nine”,…
• Tuples are sequences of symbols. numerals = ('no','one','two','three','four','five',
'six','seven','eight','nine','ten')
def bottle(b): if b==1: return numerals[b] + " green bottle, hanging on the wall" else: return numerals[b] + " green bottles, hanging on the wall"
• Like strings, tuples are immutable.
slicingFinally, we need to properly capitalise every line of the verse.
• We need to be able to slice up a string, converting only the first letter to upper-case.
At the REPL type:>>> "one".upper()>>> “one”[0:1]>>> “one"[0:1].upper()>>> "one"[0:1].upper() + "one"[1:]
Add the following function:
def caps(s): return s[:1].upper() + s[1:]
And call the function in the following two lines:
print(caps(greenBottles(bottles)))print(caps(greenBottles(bottles)))
•Slicing works on all types of sequence.
Ten Green Bottles# Ten Green Bottlesnumerals = ('no','one','two','three','four','five','six','seven','eight','nine','ten')
def greenBottles(b): if b==1: return numerals[b] + " green bottle, hanging on the wall" else: return numerals[b] + " green bottles, hanging on the wall"
def caps(s): return s[:1].upper() + s[1:]
for bottles in range(10,0,-1): print(caps(greenBottles(bottles))) print(caps(greenBottles(bottles))) print("And if " + ("that" if bottles==1 else "one") + " green bottle \
should accidentally fall,") print("There'll be "+greenBottles(bottles-1)+".")
print()
conclusionWhile we’ve covered a range of Python features, the three main features of programs are:
• Sequence
• Loops
• Conditionals
With these, we can write programs that can do anything (computable).