S206E057 -- Lecture 19, 5/24/2016, Python – an overview

S206E057 – Spring 2016
S206E057 -- Lecture 19, 5/24/2016, Python – an overview
Copyright ©2016, Chiu-Shui Chan. All Rights Reserved.
Global and local variables: differences between the two…
Global variable is usually declared at the start of the program, their global scope means they can be used in any procedure
or subroutine in the program. If it has not been redefined, it will stay with the value that was original defined without any
changes. In other words, whenever a variable is defined, its value will stay the same unless it is modified locally. See the
variable f in the following example on the left. Global variable could also be declared by the format of:
global f
Local variable is declared within subroutines or programming blocks, their local scope means they can only be used within
the subroutine or program block in which they were declared. Python deals with variables as local variables, if not declared.
So when you define variables inside a function definition, they are local to this function by default. This means, that anything
you will do to such a variable in the body of the function will have no effect on other variables outside of the function, even if
they have the same name. This means, that the function body is the scope of such a variable, i.e. the enclosing context
where this name with its values is associated.
In the following example, the value of the variable f is defined as 0 first. Thus, the first print on line 7 is 0. Then, in the
someFunction, f is re-defined locally as a string of “window”. This value is the local variable definition activating inside the
function. When the function called is called, its value is changed from 0 to a string of “window” residing within the function.
After the function completes; the value of f returns back to 0 and printed by the coding on line 16. However, if the variable f
is defined as global variable inside the someFunction, then it will have the following results.
0
window
window
It is because that f is defined as a global variable, its value remains as in global scope after the function is completed.
Please compare the output components on the left and right pictures.
Global variable
Local variable
Page 1 (5/1/2016)
Arch534 – Spring 2016
Note: It is seldom advisable to use global variables as they are liable to cause bugs, waste memory and can be hard to
follow when tracing code. The example given on the right is not considered as a good or appropriate programming style.
Other example of global and local aspect:
In Python, some of the variables could be defined as global
ones. See the example on the right.
In this example, the FloorArea is defined as 3000 square
feet, which is the building code regulation and thus defined
as global variable that won’t be changed in the whole
program after this line.
Users could input 3000 or above, then it will be switched to a
string value of “Too Big.” After the function of BuildingCode
check is completed, it will resume back to the original value
of 3000.
In this example, an if-then logical operation is also
introduced, but, it will be further explained in the next lecture.
Summaries of global versus local variables:
If you define global variables (variables defined outside of any function definition), they are visible inside all of your
functions. They have global scope. It is good programming practice to avoid defining global variables and instead to put
your variables inside functions and explicitly pass them as parameters where needed. One common exception is constants:
a constant is a name that you give a fixed data value to, by assigning a value to the name only in a single assignment
statement. You can then use the name of the fixed data value in expressions later. In other words, the property of a
constant is that it has a “getter function” to read the data, but no “setter function” to re-write the data. This essentially
protects the identifier from being changed.
Function calls:
Functions can call functions instead of just executing one function after the other. Here is the example. Two functions
defined first, then call these two separately on the left example below. On the right, we have a main function defined to call
these two functions to run. Both are the same in results. But, the right one is well organized.
In fact, in programming style, some professional programmers would use one major function to execute the entire task.
This, in fact, sets up an execution hierarchy on implementing the entire algorithm efficiently. It also helps to apply the
algorithm more user friendly when it is saved in any of open source public library.
Page 2 (5/1/2016)
S206E057 – Spring 2016
Function’s formal parameter and argument:
Values are passing through the parentheses into the
function. Here in the definition heading for functionA,
person is referred to as a formal parameter. This
variable name is a placeholder for the real value.
In the function call, the word person between the
parentheses is the argument or actual parameter.
The argument supplies the actual data to be used in
the function. So, when functionA is called, Python
associates the formal parameter name person with
the actual data John. Thus, the actual parameter
value is passed to the function for print.
String data from Rhino input method:
One way of getting input, instead from passing the
value from formal parameter into the function, is from
user keyboard input. For example:
def functionA(person):
print(person + " Bottom Up!")
def main():
userName = raw_input("First name")
print('You entered ' + userName)
functionA(userName)
main()
Here, raw_input is one of the user input functions (or mechanisms) that accepts users’ character input and returns that as
a string. The prompt string of “First name” is shown on Rhino screen as a message waiting for user’s input. Then, Python
accepts the input as its own value. The other mechanism is the function of “input” for getting number values as shown in
the following example. The input/output results are also displayed in Rhino command area, please take a look at them.
Number data input in Rhino:
A sub-function could take two arguments, passing them through the formal parameter into the statements. Inside the main
function, arguments were decided by the input command that takes user input from Rhino and defined the input by the
function of int() as the integer type.
•
•
Input([prompt]) is to get general number input from users.
Int(x, base=10) will return (or say assign) an integer object constructed from a number or a string x, or return 0 if no
arguments are given by users.
Page 3 (5/1/2016)
Arch534 – Spring 2016
•
The .format() method of the str type is an extremely convenient way to format text exactly the way you want it to.
It will fill the value of assigned variables to the curried parentheses {}.
In fact, we don’t have to apply int() function to let Python know that the input is an integer number. But, if the input number
must be integer for the related integer number operation, then it is more appropriate to use this function for avoiding
unexpected errors. See the example below.
Here is another example with a print function instead of print a variable. The result is ‘None’. It is because inside the print
call, it calls the function to print the sentence and stop. That function had not returned anything explicitly for print to do, so it
prints none to show nothing. This notion relates to the data output phenomenon.
Data output and build-in name:
Inside a function, if there is a statement of return [expression] is defined and encountered, then it exits a function, and
optionally passing back an expression to the caller. A return statement with no arguments is the same as return “None”. The
following one is a simplest form of a Python function. This function takes a string as input parameter and prints it on
standard screen.
def printme (stir):
stir = "This prints a passed string into this function."
print stir
return (stir)
print (printme(stir))
Here, “stir” is a variable. If you write the code in your
program and it doesn’t work due to the name “stir” is
not defined, then you have to declare a value for the
variable stir first to let Python recognize this defined
variable. See the example on the right.
Yet, change the name to str, then Python recognizes
it as a string and works. See the example shown on
the previous page. But, str is a built-in name of string
function.
Page 4 (5/1/2016)
S206E057 – Spring 2016
It has been explained in many articles that in Python programming convention, we would never use built-in names as
variable identifiers (variable names). Of course, it won’t confuse the program interpreter but it may confuse people reading
your code. Uncecessary use of built-in names for attributes and methods should be avoided. Another ill-effect is that
shadowing built-ins confuses syntax highlighters in most python-aware editors (vi, emacs, pydev etc). Some of the editor
tools will warn about this practice. What happen if the return statement occurs before the print statement? See the
comment part of the return function above.
Local Scope of variables inside a function:
For the logic of writing functions, it is important that the writer of a function knows the names of variables inside the function.
On the other hand, if you are only using a function, maybe written by someone unknown to you, you should not care what
names are given to values used internally in the implementation of the function you are calling. Python enforces this idea
with local scope rules: Variable names initialized and used inside one function are invisible to other functions. Such
variables are called local variables. For example, a lastFirst function with its local variable separator, but it might also have
another function that defines a separator variable, maybe with a different value like '\n'. They would not conflict. They would
be independent. This avoids lots of errors!
Important hints and notes –
The following notes are collected from Python manual for programming reference. The purposes are to provide enough
hints and knowledge for coding exercise. You might want to use them for the final project. Details could be found on the
following online page: http://www.tutorialspoint.com/python/python_quick_guide.htm. Item 10 here explains the other type of
“LIST” data structure in Python, which holds a series of data items. “List” has also been utilized in Grasshopper to contain
the coordination and geometric properties of objects in space.
1. Identifiers: Python is a case sensitive programming language. Regardless whether the word is used to define a
function name or used at anywhere, it matters. For instance Manpower and manpower are two different identifiers in
Python. Here are the conventions for Python.
•
•
•
•
Class names will start with an uppercase letter and all other identifies with a lowercase letter.
Starting an identifier (name of a variable) with a single leading underscore indicates by convention that the
identifier is meant to be private.
Starting an identifier with two leading underscores indicates a strongly private identifier.
If the identifier also ends with two trailing underscores, the identifier is a language-defined special name.
2. Reserved words: In Python, there are reserved words, which may not be used as constant or variable or any other
identifier names. You don’t have to find the list of the reserved words, which would be signified by blue color when we
type in the codes on line.
3. Lines and indentation: There are no braces to indicate blocks of code for class and function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly enforced. The number of spaces in the indentation is
variable, but all statements within the block must be indented the same amount.
4. Multi-line statements: Statements in Python typically end with a new line. Python does allow the use of the line
continuation character (\) to denote that the line should continue. Statements contained within the [], {}, or () brackets do
not need to use the line continuation character.
Total = item_one + \
item_two + \
item_three
days = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday"]
Page 5 (5/1/2016)
Arch534 – Spring 2016
5. Quotation in Python: Python accepts singe (‘), double (“), and triple (‘’’or”””) quotes to denote string literals, as long as
the same type of quote starts and ends the string.
6. Comments in Python: A hash sign (#) that is not inside a string literal begins a comment. All characters after the # and
up to the physical line end are part of the comment, and the Python interpreter ignores them.
7. Using blank lines: A line containing only whitespace is known as a blank line, and Python totally ignores it. In an
interactive interpreter session, you must enter and empty physical line to terminate a multiline statement.
8. Python variables: Variables are nothing but reserved memory locations to store values. Thus, we don’t have to
declare the variable type, just assign values to variables. There are five standard data types in Python, numbers, string,
list, tuple, and dictionary. The operand to the left of the = operator is the name of the variable, and the operand to the
right of the = operator is the value stored in the variable.
9. Python strings: Strings are identified as a contiguous set of characters in between quotation marks.
str = "Hello World!"
print str
print str[0]
print str [2:5]
print str[2:]
print str *2
print str + "TEST"
# prints complete string
# prints first character of the string
# prints characters starting from 3rd to 5th
# prints string starting from 3rd character
# prints string two times
# prints concatenated string
10. Python lists: it is the same as the string function.
list = ["abed", 786, 2.23, "john", 70.2]
tinylist = [123, "john"]
print list
print list[0]
print list[1:3]
print list[2:]
print tinylist *2
print list + tinylist
# prints complete list
# prints first element of the list
# prints elements starting from 2nd to 4th
# prints elements starting from 3rd element
# prints list two times
# prints concatenated lists
11. Python Tuples: A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values
separated by commas. Unlike lists, however, tuples are enclosed within parentheses and they could be thoughts of as
read-only lists.
12. Python dictionary: Python’s dictionaries are hash table type. They work like associative arrays or hashes found in Perl
and consist of key-valued pairs. In the pair, the first one is the key and the second one is its value.
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print tinydict['name']
print tinydict
print tinydict.keys()
print tinydict.values()
# Prints value for 'one' key
# Prints complete dictionary
# Prints all the keys
# Prints all the values
In this Lab exercises, how to define functions, various ways of making function calls, passing values to variables, the
interaction among variables, methods of data input and output mechanisms were covered in this lab exercises. Please type
and test each coding example in the Rhino Editpythonscript window to understand code writing. You should also change the
sequences of the codes to find out related computational results. Some examples of Python scripts executed in Rhino could
be found from “Help” menu inside the “EditPythonScript” window area. Rhino has its own script which is a bit different.
Page 6 (5/1/2016)
S206E057 – Spring 2016
What is the if __name__ == “__main__”
Whenever python interprets a file, it creates a variable called “main” in the system. This main component is private and the
functions declared inside the main will be run locally. If the file is imported to other files, then coding actions outside the
main component will be interpreted and executed, unless the main function is called. For instance, the first line of print in
the following example, which is outside of the main function, would always be interpreted and executed, but, not the main
function part. Unless the main part is called outside of the file. This method is commonly used in the “class” stored in
Python libraries.
File Name: first_modul.py
Second file Name: second_mudule.py
This is the first example of importing the file to the second_module without running the function main. You will see the results of “Run
from import”, that means the system skips the main function. See the output message below, particularly on the module’s name
which is the filename that serves as the name of the component, and run from import or run directly.
This is the second example of calling the function of main. Here, function call format is that use the file name of first_module as the
identifier followed by a period and the function name. See the output message. Run from import or run directly.
Page 7 (5/1/2016)
Arch534 – Spring 2016
Page 8 (5/1/2016)