Where we are and what's coming next :
Continue our discussion of functions.
Any questions?
In class, look at a python program that prints the "happy birthday" song ... in several iterations.
Then check out 99-bottles-of-beer.net ...
Finish the following example in class.
"""
factorial.py
Looking at functions, doctests, and test-driven deveopment.
"""
def factorial(n):
""" Return the factorial of n, i.e. n!, which is n * (n-1) * ... 2 * 1
>>> factorial(2)
2
>>> factorial(5)
120
"""
return 0 # This is the wrong result. Tests will fail.
def main():
print "-- factorial --"
n = int(input("What is n? (i.e. 5) "))
print("{}! is {}.".format(n, factorial(n)))
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
Discuss the difference between the following two programs.
# Version 1 : what will be printed ?
name = "Jim"
def f():
name = "Joe"
return 1
def main():
x = f()
print(" name is {}".format(name))
main()
# Version 2 : what will be printed ?
names = ["Jim", "John", "Mary"]
def f():
names[0] = "Joe"
return 1
def main():
x = f()
print(" names is {}".format(names))
main()
... and discuss what's right and wrong in the following.
def f1(x):
print(x)
def f2():
x = input(" ? ")
return x
def f3(x):
return x
y1 = f1(3)
print("y1 is '{}'".format(y1))
y2 = f2()
print("y2 is '{}'".format(y2))
y3 = f3(20)
print("y3 is '{}'".format(y3))
print("x is '{}'".format(x))
If there's time left, start discussing conditionals ... which is coming next. :)
We worked through the beginnings of "if" statements using the FizzBuzz example. What we ended up with attached.
last modified | size | ||
birthday_1.py | Sat Nov 23 2024 11:28 am | 277B | |
birthday_2.py | Sat Nov 23 2024 11:28 am | 372B | |
birthday_3.py | Sat Nov 23 2024 11:28 am | 679B | |
factorial.py | Sat Nov 23 2024 11:28 am | 774B | |
fizzbuzz.py | Sat Nov 23 2024 11:28 am | 638B |