Blocks of code, importance of indentation
Conditional statements
def limit(n, upperBound):
if (n > upperBound):
n = upperBound
return n
def evenOdd(word):
n = len(word)
if (n % 2 == 0):
return "even"
else:
return "odd"
def letterGrade(points):
if (points >= 90):
letter = "A"
elif (points >= 80):
letter = "B"
elif (points >= 70):
letter = "C"
elif (points >= 60):
letter = "D"
else:
letter = "R"
return letter
def weatherAdvice():
print "Please answer yes or no."
answer1 = raw_input("Is it cold outside? ")
if (answer1 == "yes"):
print "You'd better wear a sweather."
answer2 = raw_input("Is it raining? ")
if (answer2 == "yes"):
print "You'd better carry an umbrella."
else:
print "Good, at least it's not raining!"
else:
print "Enjoy the warm weather!"
def powersOfTwo(upperLimit):
n = 1
while (n < upperLimit):
print n
n *= 2
def functionsRace(finishLine):
print "Functions race!"
print "Function 1: y1 = 10 * x + 50"
print "Function 2: y2 = x * x - 100"
print "x\ty1\ty2"
x = 0
y1 = 0
y2 = 0
# while loop with conjunct condition
while (y1 < finishLine and y2 < finishLine):
y1 = 10 * x + 50
y2 = x * x - 100
print "%d\t%d\t%d" % (x, y1, y2)
x += 1
if (y1 > y2):
print "Function 1 wins!"
elif (y1 < y2):
print "Function 2 wins!"
else:
print "It's a tie!"
Chapter 2 (pp. 29-36).
Chapter 2: problems 1, 2, 6, 9, 17, 18, 19.