<<

S206E057 – Spring 2021

S206E057 -- Lecture 20, 5/25/2021, Python – an overview

Copyright © 2021, 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 means that they can be used in any procedure or subroutine in the program. If the has not been redefined, it will stay with the value that was originally defined without any changes. So, 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 following left image. Alternatively, 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 inside a function as local variables, if it is not declared outside the function. So when we define variables inside a function definition, they are local to this function by default. This means that anything we 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. Thus, the function body is the scope of a .

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 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 from inside the function, its value remains as in global scope after the function is completed. Please compare the output components on the left (local) and right (global) pictures.

Global variable

Local variable

Page 1 (5/24/2021) S206E057 – Spring 2021

Note: The variable f on left is defined as 0, and redefined in somefuntion to window locally. After the function completed, its value is 0 again as a global aspect. For the example on the up right, 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 above right is not considered as an appropriate programming style. Particularly, it resides inside a function.

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 assumed to be 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 introduced, which 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 the functions. They have global scope. It is a good programming practice to avoid defining global variables and instead to put your variables inside functions and explicitly pass them as parameters where needed.

Function calls:

Functions can call functions instead of just executing one function after the other. Here is the example. Two functions are 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 .

Page 2 (5/24/2021) S206E057 – Spring 2021 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 it 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 a valid Python expression and returns the evaluated result, or getting number values as shown in the following example. The input/output results are also displayed in Rhino command area.

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. One example of getting integer input is the function of int() to specify input .

• Prompt in Input([prompt]) is to prompt users with given message as a reminder. • Users could type [x*5 for x in range (2, 10, 2)], with results of [10, 20, 30, 40], details please see lecture 18, p. 6. Page 3 (5/24/2021) S206E057 – Spring 2021

• 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 argument is given by users. • 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 {}.

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 related integer number operation, then it is appropriate to use this function for avoiding unexpected errors. 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 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/24/2021) S206E057 – Spring 2021 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, , 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” 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 . 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 indicates by convention that the identifier is meant to be private. • Starting an identifier with two leading 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 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"]

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. Page 5 (5/24/2021) S206E057 – Spring 2021

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 # prints complete string print str[0] # prints first character of the string print str [2:5] # prints characters starting from 3rd to 5th print str[2:] # prints string starting from 3rd character print str *2 # prints string two times print str + "TEST" # 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 # prints complete list print list[0] # prints first element of the list print list[1:3] # prints elements starting from 2nd to 4th print list[2:] # prints elements starting from 3rd element print tinylist *2 # prints list two times print list + tinylist # 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 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'] # Prints value for 'one' key print tinydict # Prints complete dictionary print tinydict.keys() # Prints all the keys print tinydict.values() # 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 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 differs from Python and is not that popular in our architecture profession.

Page 6 (5/24/2021) S206E057 – Spring 2021 Notions of data input/output

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 function component will be interpreted and executed; but not the statements inside the main function, unless it 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 when the file is browsed. But, the main function part is not touched. However, if the main part is called from the file that calls it, then it is executed. This method is commonly used in the special Python notion of “class”, which is how to build up Python libraries. Here are the examples.

File Name: first_module.py

Second file Name: second_module.py

This is the first example of importing the file of first_module to the second_module and call the main function in the first_module file after it is read line by line. You will see the results of “Run by importing the first_module file” had shown, 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 the file. Yet, the second run of the second_module file will not run the file again, but, just three prints.

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.

Note: To run the two files, we have to save the files in the same folder, the Python editor and Rhino, and re-open the files. Under this method, the system could find the file and execute them correctly. Page 7 (5/24/2021) S206E057 – Spring 2021

Below are the similar program exercises. The first two images are tips for executing programs transparently, whereas the last two are main functions.

The first run of the file BBB will have the first line of AAA printed. It will not be printed on the following runs. Output of AAA will be released after the file completed executions.

#File name: number.py #File name: name.py import name def functionA (APerson): #newName = name.main() print (APerson + ", Bottom Up!") newName = name.functionC() def functionB (BPerson): def sumProblem (x,y,newName): InputName = raw_input ("Second Name: ") sum = x + y print ("You entered " + InputName) sentence = "The sum of {} and {} is {}. " .format(x,y,sum) return InputName print (newName, sentence) def functionC(): def main(newName): InputName = raw_input ("Name please: ") a = int(input("Enter an integer x: ")) return InputName b = int(input("Enter an integer y: ")) sumProblem(a,b,newName) def main(): userName = raw_input ("First Name") if __name__ == "__main__": print ("You entered " + userName) main(newName) functionA(userName) print ("Cheers! " + functionB('Virginia')) return functionC()

if __name__ == "__main__": main()

Page 8 (5/24/2021)