S206E Lecture 19, 5/24/2016, Python an overview

Similar documents
Basic Syntax - First Program 1

Python - Variable Types. John R. Woodward

Introduction to Python

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

Python memento TI-Smart Grids

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

COLLEGE OF ENGINEERING, NASHIK-4

Full file at

Key Differences Between Python and Java

Python in 10 (50) minutes

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

The current topic: Python. Announcements. Python. Python

Java Bytecode (binary file)

Data Types and Variables in C language

Variables, expressions and statements

Full file at C How to Program, 6/e Multiple Choice Test Bank

Basic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017

The C++ Language. Arizona State University 1

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Lab # 2. For today s lab:

IT 374 C# and Applications/ IT695 C# Data Structures

Introduction to Python

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CSCE 120: Learning To Code

Python I. Some material adapted from Upenn cmpe391 slides and other sources

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

Fundamentals of Programming Session 4

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

PREPARING FOR THE FINAL EXAM

Algorithms and Programming I. Lecture#12 Spring 2015

Java+- Language Reference Manual

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Chapter 17. Fundamental Concepts Expressed in JavaScript

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Introduction to Bioinformatics

Starting. Read: Chapter 1, Appendix B from textbook.

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Variable and Data Type I

CSC105, Introduction to Computer Science I. Introduction. Perl Directions NOTE : It is also a good idea to

Python Input, output and variables. Lecture 23 COMPSCI111/111G SS 2018

Python at Glance. a really fast (but complete) ride into the Python hole. Paolo Bellagente - ES3 - DII - UniBS

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

UEE1302 (1102) F10: Introduction to Computers and Programming

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

61A Lecture 2. Friday, August 28, 2015

CS1 Lecture 3 Jan. 18, 2019

Some material adapted from Upenn cmpe391 slides and other sources

8. Control statements

Fundamentals of Programming. Lecture 3: Introduction to C Programming

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

VARIABLES. Aim Understanding how computer programs store values, and how they are accessed and used in computer programs.

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

cs1114 REVIEW of details test closed laptop period

Variable and Data Type I

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

Accelerating Information Technology Innovation

class objects instances Fields Constructors Methods static

1. What type of error produces incorrect results but does not prevent the program from running? a. syntax b. logic c. grammatical d.

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

Topic 1: Introduction

Scripting Languages. Diana Trandabăț

Final thoughts on functions F E B 2 5 T H

Scripting Languages. Python basics

CPSC 217 Assignment 3

S206E Lecture 23, 5/26/2016, Interaction between Python and Grasshopper

Objectives. In this chapter, you will:

Table of Contents EVALUATION COPY

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 3: SEP. 13TH INSTRUCTOR: JIAYIN WANG

Python Input, output and variables

Welcome to CS61A! Last modified: Thu Jan 23 03:58: CS61A: Lecture #1 1

Lecture 5 8/24/18. Writing larger programs. Comments. What are we going to cover today? Using Comments. Comments in Python. Writing larger programs

Lecture 3. Input, Output and Data Types

S206E Lecture 21, 5/26/2016, Python classes

SMURF Language Reference Manual Serial MUsic Represented as Functions

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

JAVASCRIPT AND JQUERY: AN INTRODUCTION (WEB PROGRAMMING, X452.1)

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

CPS122 Lecture: From Python to Java

Python Input, output and variables. Lecture 22 COMPSCI111/111G SS 2016

CSI33 Data Structures

Senet. Language Reference Manual. 26 th October Lilia Nikolova Maxim Sigalov Dhruvkumar Motwani Srihari Sridhar Richard Muñoz

Chapter 2 Basic Elements of C++

Variables, Constants, and Data Types

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

Lecture Programming in C++ PART 1. By Assistant Professor Dr. Ali Kattan

Copyright. Trademarks Attachmate Corporation. All rights reserved. USA Patents Pending. WRQ ReflectionVisual Basic User Guide

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

Introduction to: Computers & Programming: Review prior to 1 st Midterm

ENGR 101 Engineering Design Workshop

CS1 Lecture 3 Jan. 22, 2018

61A Lecture 2. Wednesday, September 4, 2013

1 Lexical Considerations

Access Intermediate

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Chapter 2: Introduction to C++

Lecture 02, Fall 2018 Friday September 7

Chapter 2: Special Characters. Parts of a C++ Program. Introduction to C++ Displays output on the computer screen

Lexical Considerations

Transcription:

S206E057 Spring 2016 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 S206E057 -- Lecture 19, 5/24/2016, Python an overview 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. Page 6 (5/1/2016) 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 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.

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)