
|
Lesson 9 Notes: Iteration (loop-de-loops)
- Print on Same Line
- Adding a comma at the end of a print statement line will make the next print command appear on same line
- Example:
print num1, "+", num2, "=",
answer = input("")
- While …
- The keyword while can be used to create a command loop.
- while statements need an "incremented counter"
- Example:
while x<10:
print x
x = x+1
- Generalizing
- To make sections of code reusable, instead of using constant values, use variables.
- Example (not generalized):
while x<12:
print 2 *x
x=x+1
- Example (generalized):
while x< max_num:
print num*x
x = x+1
- Making Tables
- Tables can be created using the tab \t escape code in a string.
- The "tab" keeps items lined up real pretty
- Example:
while x < 10:
print item1, "\t", item2
x = x+1
- Review
- How can you make two lines of code print on same line?
- What code can be used to create a well-aligned table?
- How do you make a section of code repeat itself?
- Give an example of how the principle of generalization can be applied.
Restricted access |