Download presentation
Presentation is loading. Please wait.
Published byNathaniel Arron Morgan Modified over 9 years ago
1
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON FUNCTIONS REVISITED Jehan-François Pâris jfparis@uh.edu
2
Overview We will discuss scope issues
3
Refresher Very easy Write – def function_name ( parameters ) : statements return result Observe the column and the indentation REQUIRED!
4
What it does Function Parameters Result
5
Example (I) Function titlecase: –Converts a string to “Title Case” format Same as MS Word –Words in the stringwill Start with an upper case letter All other letters will be lower case –No special handling of articles and short prepositions
6
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
7
Example (III) # continuation of previous slide if outstring[-1] == " " : outstring = outstring[0:-1] return outstring
8
A problem What if the variable names – stringlist – outstring – item – newitem were used elsewhere in the program? What would happen?
9
The answer Nothing What happens in Las Vegas, stays in Las Vegas What happens inside a function stays inside the function
10
How? Python creates new instances of – stringlist – outstring – item – newitem that only exist inside the function
11
Example def donothing() : k = 5 k = 0 donothing() print(“k = “ + str(k)) Program will print k = 0
12
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
13
Example def dosomething() : global k k = 5 k = 0 dosomething() print(“k = “ + str(k)) Program will print k = 5
14
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
15
Disadvantages Updating variables “on the sly” is very dangerous –Can—and often will—confuse the reader –Will cause hard to find errors
16
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
17
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)
18
Solution def h(a, b) : return 2*a*b/(a +b)
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.