Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS REVISITED Jehan-François Pâris [email protected] Overview • We will discuss scope issues Refresher • Very easy REQUIRED! • Write – def function_name(parameters) : statements return result • Observe the column and the indentation What it does Parameters Function Result Example (I) • Function titlecase: – Converts a string to “Title Case” format • Same as MS Word – Words in the string will • Start with an upper case letter • All other letters will be lower case – No special handling of articles and short prepositions Example (II) • def titlecase (instring) : # converts instring into Title Case stringlist = instring.split(" ") outstring = "" # empty string for item in stringlist : newitem = item[1].upper() + item[1:].lower() outstring+= newitem + " " # still need to do some cleanup Example (III) • # continuation of previous slide if outstring[-1] == " " : outstring = outstring[0:-1] return outstring A problem • What if the variable names – stringlist – outstring – item – newitem were used elsewhere in the program? • What would happen? The answer • Nothing What happens in Las Vegas, stays in Las Vegas What happens inside a function stays inside the function How? • Python creates new instances of – stringlist – outstring – item – newitem that only exist inside the function Example • def donothing() : k=5 k=0 donothing() print(“k = “ + str(k)) • Program will print k = 0 The exception What happens in Las Vegas, stays in Las Vegas UNLESS you post in on Facebook or Youtube What happens inside a function stays inside the function UNLESS you specify the variable is global Example • def dosomething() : global k k=5 k=0 dosomething() print(“k = “ + str(k)) • Program will print k = 5 Advantages • Some variables are inherently global – Useful in simulations of complex systems • You can pass “invisible parameters” to a function – Some people will think you are too lazy to pass them as parameters Disadvantages • Updating variables “on the sly” is very dangerous – Can—and often will—confuse the reader – Will cause hard to find errors The verdict • Do not use global variables in your functions unless you have a good reason to do so • Python default option is the right one What happens inside a function should stay inside the function Exercise • Write a function that return the harmonic mean h of two numbers (a and b) – 1/h(a, b) = 2(1/a + 1/b) Solution • def h(a, b) : return 2*a*b/(a +b)