Variables in Python function1
parameters
function2
local variables
return results
local variables
Global Variables # global variable globNum = 17 def func1(x): global globNum globNum += x//2 return x**2
global variables (not inside a function)
def func2(y): global globNum globNum *= y func1(y-5) Legal, but usually a bad idea: confusing code. Functions should interact using parameters & results. CISC 121 winter 2011, Intro3
1
Global Constants
2
Confusing Python Rules: 1
LIMIT = 100 # constant
# global variable counter = 17
def test(x): if x > LIMIT or x < -LIMIT: print("error:", x, "out of range")
def func(x): global counter # Add to the global variable. counter += x//2 return x**2
No Python syntax for constants: use upper-case & comment Global constants are OK
CISC 121 winter 2011, Intro3
CISC 121 winter 2011, Intro3
3
CISC 121 winter 2011, Intro3
4
Confusing Python Rules: 2
Confusing Python Rules: 3
# global variable counter = 17
# global variable counter = 17
def func(x): # counter not declared global
def func2(x): counter = 42 # counter is local return x**3
# Add to the global variable. counter += x//2 # error! return x**2
CISC 121 winter 2011, Intro3
5
CISC 121 winter 2011, Intro3
Confusing Python Rules: 4
Advice For Sanity
# global variable counter = 17
1. Avoid global variables whenever possible. Use parameters & return results. 2. For CISC 121 marked assignments, we will deduct points for global variables unless specified in the assignment. 3. When you use a global variable in a function, always use a global declaration. 4. When you initialize a global variable (outside of functions), document how it will used & by what functions.
def func3(x): print(counter) # Python assumes global return x**4
CISC 121 winter 2011, Intro3
6
7
CISC 121 winter 2011, Intro3
8
Programming Style
Example
A useful program must have all of the following properties: ● performs correctly ●
performs in a reasonable amount of time, using a reasonable amount of memory
●
is written so that it may be easily understood and modified
Look at style1.py – style4.py. Which one would you rather work with?
Reality for any useful real-world program: ● People will find bugs ●
People will want changes
●
Modifications often aren't done by original programmers
●
Most real-world programs are written by teams
CISC 121 winter 2011, Intro3
9
CISC 121 winter 2011, Intro3
Who Will Read Your Program? ●
you: while writing and debugging
●
others: while helping you write & debug
●
co-workers: while writing other parts of program
●
you/others: later when modifying, debugging
10
What Can You Assume? You may assume your reader: ● knows Python ●
knows technical background for your problem
●
knows common algorithms/techniques (or can look them up)
Do not assume your reader: ● is you
CISC 121 winter 2011, Intro3
11
●
can read your mind
●
automatically understands how you're trying to solve the problem
CISC 121 winter 2011, Intro3
12
Elements of Style
Elements of Style
1. Organization Break up your program into functions. High levels of nesting: consider making inner part into a separate function.
2. Vertical Space: To help the eye separate parts of program. ● 2 blank lines between functions ●
1 blank line to separate logical parts of long functions
Very long function without much nesting: Consider dividing into consecutive parts.
CISC 121 winter 2011, Intro3
13
Elements of Style
In general, a more informative variable name is better. But.... Single letters are traditional in numeric loops: for i in range(1,10):
less good names: studentnumber student id stdNum
Sometimes a more informative name is possible: for year in range(year1+1,year2): If a parameter is just a number, OK to give it a one-letter name (x or n as in a math formula)
bad names: s num studentIdentificationNumber
CISC 121 winter 2011, Intro3
14
One-Letter Variable Names
3. Meaningful variable names good names: studentNumber studentNum studentId idNumber
CISC 121 winter 2011, Intro3
If a parameter is a number representing a length or weight or count, give it a name that expresses that
15
CISC 121 winter 2011, Intro3
16
Variable Name Example
Elements of Style
def root(n): """Finds the square root of n within .001, or 0 if n is negative. Uses Newton's method of successive approximations. """
4. Good indentation. Goal of indentation: makes program structure easy to see ● from start of a function or if or loop: where does it end? Indent by at least 2 spaces, preferably 3 or 4
if n < 0: return 0 guess = n / 2.0 while True: oldguess = guess guess = (oldguess + n/oldguess) / 2 if abs(guess-oldguess) < .001: # close enough return guess
CISC 121 winter 2011, Intro3
Be consistent (not 2 spaces here, 4 spaces there)
17
CISC 121 winter 2011, Intro3
Elements of Style
Where Do You Need Comments?
5. Comments Comments are not a substitute for the first 4 elements! They provide additional information & help to the reader.
CISC 121 winter 2011, Intro3
18
19
●
at the beginning of the program: ● what does the program do? ● who wrote it and when?
●
at the beginning of each class
●
beginning of each function (or in a docstring): ● what does the function do? ● what parameters does it take? ● what result does it return?
●
blocks of code that aren't obvious
●
introduction of variables that need more explanation than the variable name provides
CISC 121 winter 2011, Intro3
20
Too Many Comments?
Readability In The Workplace
Too many / unnecessary comments: just as bad as too few!
Many software companies have coding standards, code reviews.
# number of students in the class numStudents = ... # increment x by one x += 1
CISC 121 winter 2011, Intro3
21
CISC 121 winter 2011, Intro3
22