Intro to
Programming
(with Python)

Fall 2018
course
site

Tue Oct 2 - functions

Where we are and what's coming next :


Continue our discussion of functions.

Any questions?

In class, write 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()

If there's time left, start discussing conditionals ... that's coming next. :)

https://cs.marlboro.college /cours /fall2018 /python /notes /chap6b
last modified Tue December 5 2023 8:22 am

attachments [paper clip]

  last modified size
TXT birthday_1.py Tue Dec 05 2023 08:22 am 277B
TXT birthday_2.py Tue Dec 05 2023 08:22 am 372B
TXT birthday_3.py Tue Dec 05 2023 08:22 am 679B
TXT factorial.py Tue Dec 05 2023 08:22 am 693B