History
Inthe 1950's, FORTRAN and Cobol were among the first "high level"
languages to be developed. Until then, programmers had used machine
languages and assembly languages that were specific to each processor.
The language C did not appear until the 1970's.
for loops
for count in range(10):
print count
This is shorthand for
count = 0
while count < 10:
print count
count += 1
You can also use other lists or strings as the index set
for ch in 'abccba':
if ch in 'aeiou':
print ch, ' is a vowel'
breaking out of a whle loop
A loop is like a rotary with a single entry point, but you don't
have to exit at the same point.
sum = 0.0
count = 0
num = input("Enter a number ")
while num != -1:
sum += num
count += 1
num = input("Enter a number ")
av = sum/count
another scheme is
while True:
num = input("Enter a number ")
if num == -1:
break
sum += num
count += 1
av = sum/count
Coercing ints and strings into boolean
while 1
while 'on'
Pythagorean triples
3, 4, 5 is a Pythagorean triple. How do we enumerate them?
Using while loops?
Using for loops?
Functions
You have already used functions: random.randint(1, 6), math.sin(x),
input("Enter something"), float(sum), open(filename)
You can expand the language by writing new functions. For example,
minOfThree(a,b).
def minOfThree(a, b):
< block of statements>
def takes your block of code and makes it into a function that you can call
Testing your code
See week3TestMin.py
It is a good practice to generate tests for functions and (later) modules
before you write them.
Recursion
Let's compute factorial:
- what is 1! ?
- what is 2! ?
- what is 3! ?
- what is n! ?
A factorial function can be written that calls itself. It behaves as if it
cloned itself.