SD322308-L Class Handout SD322308L Gui Talarico
SD322308-L Class Handout SD322308L Gui Talarico
SD322308-L Class Handout SD322308L Gui Talarico
Learning Objects
🙈 Learn how to set up a programming environment for Python
🖥 Learn how Python code is interpreted and executed
📝 Learn how to read and write files using Python
📘 Learn the basic data types and flow-control features of Python
Description
This is an introductory class to Python—no previous experience required. The
class will walk through basic concepts of Python and how to set up a Python
programming environment. It will cover Python’s basic data types, flow control
mechanisms, and some of the native libraries that you can use to develop your
own automation tools in Python. At the end of the session, attendees will be able
to develop a working Python script that can read and write files that can be used
to transfer data between different platforms.
Speaker
Gui Talarico is a Software Engineer at Airbnb's Samara Design Studio. Prior to
joining Airbnb, he was a Software Engineer at WeWork where his work focused on
the integration of software development, physical space data, and design
processes.
Beyond his professional work, Gui is an active contributor to open source
projects, and online communities, including is Revit API Docs, an online
Links
Presentation
Github Repo
Python Overview
What is Python?
Python is a high-level, general-purpose, open-source programming language. The
language is widely used in a variety of fields, including mathematics, data-
science, and web-development.
Python is also an interpreted language, meaning, its code is interpreted and does
not require compilation. The program that interprets and executes python source
code is called an Interpreter.
The most popular Python Interpreter implementation it’s CPython, which is written
in the language “C”. CPython is the most popular, or reference Python
implementation, and will be the implementation referenced in this session
What is IronPython?
IronPython is an implementation of the Python specs created written in C#. Fun
fact, "Iron" stands for "Implementation Runs On .NET", according to one its
maintainers, Alex Earl (Talk Python to Me, Episode #74 Past, Present, and Future
of IronPython @ 9 20 .
The C# implementation allows the interpreted python code to interact directly
with other applications compatible with Microsoft's .NET framework C#, F#, VB,
etc) through the Common Language Runtime ( module).
clr
Python code that depends on libraries that rely on native C code cannot run in
IronPython Numpy, Pandas, etc).
Another disadvantage of IronPython is that development is several years behind
CPython. The latest stable release is IronPython 2.7, while CPython is 3.8. Python
2.7 will reach end-of-life in 2020 and will no longer supported by the python
community.
Getting Started With Python 3
💡 Weherewillis because
not be using IronPython in this session. The topic is covered
IronPython is used widely in AEC industry so it's helpful
to understand the differences and when one might chose one over the
other.
💡 *CPython
There are is experimental project called PythonNet which allows
to integrate with .NET's clr. It has some limitations, it does
work as advertise and has shown substantial improvement over the last
few years
Learning Journey
Learning a new language is no easy feat. It takes time and a lot of patience. Each
person will have their own unique journey and destination. Some may want to
simply automate some work tasks, while others want change careers and become
a software developer.
💡 Iflearning
Python is not your first language, you are in luck! You can expect your
curve to be substantially shallower!
As you start your learning journey, you might also enjoy reading this article by
Erik Trautman
Why Learning to Code is So Damn Hard. The article offer interesting analogies
and insights into the challenges we go through when learning a new programming
language.
Below are two relevant PEPs (Python Enhancement Proposal) that are considered
important documents in establishing the language's guiding principles:
Idiomatic Python
Written by Jeff Knupp, this book documents the good and bad ways of writing
python. It's short and simple but fun to read and I highly recommend. You can get
a sneak peak of the content on this Blog Post. Learning resources like this are
always a great way to immerse yourself into the language, practice reading
source code, learn better patterns.
Application Patterns
Complex Application patterns are beyond the scope of this session. For
beginners, the best way to improve your ability to develop clean and
maintainable code is write code, iterate, and read application source code.
A good place to read application source code is the Awesome Python Application
repository.
There are two primary ways to debug our program: print it's output, or insert a
breakpoint and inspect the values interactively. While the "print" method is easiest
and most common, using breakpoints is more powerful and often more effective.
Later into the session will will explore both methods.
Getting Help
Learning how to find solutions online or how to ask for help is one of the most
valuable skills a beginner can have. If you run into an error, often a simple search
will help you find the solution. However, if the issue you have is specific to your
application, or if you are not sure how to build something, being able to ask a
good question is key.
A well asked question is more likely to a get a fast and good response, while a
poorly structured question will likely be ignored or even removed from Q&A
platforms.
This post on Stackoverflow outlines some important pointers to consider:
https://stackoverflow.com/help/how-to-ask
If your issue is related to an open source library, the issues section on it's
repository is also a great place to search for solutions.
Tutorials
One you are familiar with the basic syntax, tutorials are an excellent next step to
learn how language constructs are assembled to together to achieve a purpose.
Learning Checklist
If you are not sure where to start, you can use the list below:
💡 Why 3.7.5 ? Python3.8.x was released very recently Oct 2019 and you
more likely to encounter library compatibility issues. 3.7.5 is the latest
stable version of the 3.7.x releases
Installation Steps
If you comfortable following the Installation wizard on your own, go for it. If you
need additional help, you can refer to the step-by-step instructions on Real
However you decide to setup your installation, just make sure you check the box
"Add Python 3.x to PATH". This will ensure the Python interpreter can be found
when you type on the command prompt
python
C:\>dir
# list files and directory
C:\>mkdir test
C:\>cd test
# changes current directory to test
C:\test> explorer .
# open a windows explorer window at current directory
You can create the directory manually from using Windows Explorer, you can also
do this quickly from the command prompt:
c:\>mkdir au-2019-python
While you can save your files anywhere, it's important to understand the their
location affects how the code is executed. The interpreter will look for the
following
c:\>python <relative-path-to-a-python-file>
# Ie. from c:\, you need to enter the full file path
c:\>python au-2019-python/test.py
Alternatively, you can cd to where your files are and run them from there
If you try to run a file with the incorrect location, Python will tell you:
c:\>python test.py
python: can't open file 'test.py': [Errno 2] No such file or directory
Editors
Python code can be written using any text editor, although most developers use
robust text editors like Atom, Sublime, Visual Studio Code, or Notepad ++.
Integrated Development Environments like PyCharm or Visual Studio can also be
used, however, I find they are often intimidating for beginners.
You can also write your code directly in embedded editors such as the one
provided by Dynamo, although they usually lack many of the features provided
by the alternatives above like code completion, code linting, and file
management.
You should use whichever editor feels more intuitive to you. This class will teach
use VS Code editor and execute code directly through the Python Interpreter.
Launching VSCode
You can launch Visual Studio Code from anywhere, but I often prefer to launch it
from a terminal. This ensures the current directory is set correctly.
c:\au-2010-python>code .
Launching a Terminal
To launch a new terminal go to the Terminal and click New Terminal.
For this session we will run the interpreter and then execute python code one line
at the time. To start a new interpreter session just type python
Note the caret indicates the code is being run from an interpreter in
>>>
interactive mode.In some examples, blank lines might follow to indicate the
output or result of the line executed.
c:\au-2010-python> python
Python 3.7.3 (default, Jun 4 2019, 11:29:12)
[Clang 11.0.0 (clang-1100.0.20.17)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2 + 2
4
# c:\au-2010-python\hello.py
print("Hello!")
Language Primitives
Now that we have a Python installation setup, an editor, and a terminal, we will
dive into the language by playing with it interactively.
Print
Python programs can output values using the function . The print function
print()
takes an argument (the value inside the parenthesis) and outputs it's
representation below.
💡 There
below
many other built-in functions available - for a full list see the link
https://docs.python.org/3/library/functions.html#built-in-funcs
Commenting
Getting Started With Python 18
A hash or pound character (#) can be used to tell the interpreter to ignore all
subsequent characters in the same line. This is commonly used to add comments
to yourself and others.
>>> # This line will not be executed
Integer
Positive or negative whole numbers with no decimal points.
>>> print(5)
5
>>> print(-10)
-10
Float
Getting Started With Python 19
Positive or negative Integer values, with decimals separated by a dot.
>>> print(5.5)
Boolean
Valid boolean-type values are True and False. These types are case sensitive, so
True is not the same as true. In the example below we use the operator to is
List
Array-like container object that can hold a collection of data-types including
other lists (nested lists). Unlike other languages, Python lists can hold different
data-types mixed together, although that’s often not a good idea. Lists are
represented with square brackets. When lists are created, they are often
immediately assigned to a variable, as in the examples below.
>>> numbers = [1,2,3]
>>> points = [[0,0,0], [2,3,4], [5,5,5]]
>>> objects = ['Desk', 'Chair', 'Lamp']
>>> print(objects)
['Desk', 'Chair', 'Lamp']
List items can be accessed using its index wrapped in square brackets. Indexes
start at 0.
Dictionary
Container-like objects that holds data using key-value pairs. Strings are often
used as keys, but they can be of other data-types - including integers and floats.
Dictionaries are represented using curly braces, with key-colon-value pairs,
separated by commas.
>>> elevations= {'Level 1': 10.0, 'Level 2': 25.0}
>>> coordinates = {'absolute': [0,0,0], 'relative': [20,20,0]}
>>> person = {'Name': 'Mark', 'Age': 20, 'Address': '123 Street'}
None
None is a unique object type that’s used to represent an undefined value or the
absence of a value. None is also case-sensitive.
>>> active_view = None
some operators can perform implicite type castings, not all combinations are
possible.
>>> 2 * 2
4
>>> 'Hello ' + 'You' + "!"
'Hello You!'
Statements Overview
In contrast, statements are basically everything else, often associated with an
action. Common statements are variable assignment ( x = 2 ), and other flow-
control features such as (if, else, for, etc).
>>> x = 3 # Assign the value 3 to the variable x
>>> if x == 3: # Checks if the variable x is equal to the value 3
... x = 5 # Assign the value 5 to the variable x
Assignment Statement
A single ‘=’ symbol is used to assign a value to a variable name. This is different
than two ‘==’, which is a check for equality, as shown above.
>>> x = 1
>>> y = 3
>>> print(x+y)
4
White Space
One of the most controversial and loved features of Python is the obligatory use
of white space. Unlike other languages which use brackets to group blocks of
code, Python uses spaced indentation. While "tab" characters are allowed, the
official Python Style Guide advise use of 4x space characters instead.
Using the same example from above, note how indentation is used to control
execution flow:
>>> x = 3
>>> if x == 3:
... #### note
... # Only do this if x is equal to 3
... else:
... # Do this if x is NOT EQUAL 3
Methods
Methods are functions defined and stored within an object. Many built-in data-
types come with pre-defined methods built-in. That enables us to call or apply a
function directly to an object. As you learn how to define your own data-types,
you can create your own method, but for now we will stick with using methods
defined by the built-in types.
In the examples below, we use the a list's method to append a new item,
append
A list of all String Methods and List Methods are detailed in the official Python
documentation.
Classes
Classes are recipes for custom data-types. For instance, one could create a class
called . An instance of this class might have a property
Door door.is_open that
returns or
True False, a property that returns its width, and a method
door.width
Classes are fairly advanced topic and further details are beyond the scope of
this this course, but we will include an example below for your reference. You can
read more about Python Classes on the official docs at
docs.python.org/3/tutorial/classes.html
class Door():
""" This class represents a Door """
def open(self):
self.is_open = True
def close(self):
self.is_open = False
Imports
Imports can be used to load additional modules, classes, or functions into your
script. These can come from another script you have written, or from the Python
Standard Library. The standard library is a large collection of packages that is
shipped with Python to extend functionality. For instance, the math module
contains additional math-related tools; the time module gives you tools for
working with time. You can read more about all the modules available in the
Standard library on https://docs.python.org
Below are two simple examples that use the os and sys module to access
functionality related to the operating system and the interpreter:
>>> import os # imports the os module
>>> os.listdir('C:/') # call listdir method to get files in directory
['Program Files', 'ProgramData', 'Users', 'Windows', 'Logs' ]
Note on * Imports
It’s worth mentioning that although the template uses the syntax from
Namespace import * , this is generally considered bad practice by the Python
Community. The asterisk at the end tells Python to load all classes and methods
inside the module. Depending on the namespace, you could be loading hundreds
or even thousands of identifiers into the context of your script. This practice also
has the following disadvantages:
1. Loading all modules can cause a namespace conflict. For example, if another
module also contains a class with the same name, the first one loaded will be
Getting Started With Python 27
overwritten.
2. As objects loaded are used throughout our code, it’s hard for other
programmers to tell from which one of the Assemblies/Namespaces the
object came from.
A better solution is to either load only the class you need, or to reference them
using the parent module. For example, if you want to use the Circle and Vector
classes, you could use
Hands on Project
See https://github.com/gtalarico/au-2019-python for updated Handout