Intro to
Programming
(with Python)

Fall 2019
course
site

Tue Oct 8 - more on functions

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.

https://cs.marlboro.college /cours /fall2019 /python /notes /chap6b
last modified Wed April 24 2024 8:44 pm

attachments [paper clip]

  last modified size
TXT birthday_1.py Wed Apr 24 2024 08:44 pm 277B
TXT birthday_2.py Wed Apr 24 2024 08:44 pm 372B
TXT birthday_3.py Wed Apr 24 2024 08:44 pm 679B
TXT factorial.py Wed Apr 24 2024 08:44 pm 774B
TXT fizzbuzz.py Wed Apr 24 2024 08:44 pm 638B