Together With Python
Together With Python
Computation, Visualization and Reporting
Introduction
Nirjhar Dhang
√
Version : 1.732 : 3
Created on : March 09, 2011
Last revision : January 11, 2025
Introduction to Python
Students are encouraged to use Python
for preparation of assignments of the following subjects:
Design of Reinforced Concrete Structures
Bridge Engineering
Structural Health Monitoring and Control
Biomechanics
Construction Planning and Management
High Rise Structures
Introduction to Civil Engineering and Materials
Civil Engineering and Sustainability
What is Python?
What is Python?
Created in 1990 by Guido van Rossum while at CWI, Amsterdam
An interpreted, object-oriented, high-level programming
language with dynamic semantics.
Simple and easy to learn.
Open source, free and cross-platform.
Provides high-level built in data structures.
Useful for rapid application development.
Can be used as a scripting or glue language.
Emphasizes readability.
Supports modules and packages.
Bugs or bad inputs will never cause a segmentation fault
Usage of Python
Usage of Python
shell tools : system admin tools, command line programs
extension-language work
rapid prototyping and development
graphical user interfaces
database access
distributed programming
Internet scripting
How to learn a language
How to learn a language
Please note:
Only as a minor, one can afford
to spend the whole semester or a year
to learn a computer language
How to learn a language
Classic Hello program
Variables
Condition
Loop
Function
Class
Module
Input/Output
Classic Hello program
Classic Hello program
print "Hello"
Classic Hello program
print "Hello"
Hello
Classic Hello program : Python 3
print("Hello")
Classic Hello program : Python 3
print("Hello")
Hello
Variables
Variables
No need to declare
Need to assign (initialize)
use of uninitialized variable raises exception
Everything is a "variable": even functions, classes, modules
Not typed
if support == ’fixed’:
displacement=0.0
else:
displacement=’undefined’
Variables
x = 10
y = ’Sapiens’
print(x)
print(y)
10
Sapiens
Numbers
Python Numbers
There are three numeric types in Python:
int
float
complex
x = 1
y = 2.1
z = 3j
print(type(x))
print(type(y))
print(type(z))
<class ’int’>
<class ’float’>
<class ’complex’>
Usage of [] {} () in Python
Usage of [] {} () in Python
[] List L=[1,2,3,’A’,’B’]
{} Dictionary D={’id’:1,’x’:5.0,’y’:2.0}
() Tuple P=(1,2,3)
Condition
Condition
if marks >= 90:
grade=’Ex’
elif marks >= 80:
grade=’A’
elif marks >= 70:
grade=’B’
elif marks >= 60:
grade=’C’
elif marks >= 50:
grade=’D’
elif marks >= 35:
grade=’P’
else:
grade=’F’
Block
Block
Python programs get structured through indentation, i.e. code
blocks are defined by their indentation.
This principle makes it easier to read and understand Python
code
Loop
Loop
For loop
for i in range(5):
print ( i,i*i )
>>>
0 0
1 1
2 4
3 9
4 16
Loop
While loop
i=0
while i < 5:
print ( i,i*i )
i=i+1
>>>
0 0
1 1
2 4
3 9
4 16
Loop
For loop While loop
for i in range(5): i=0
print( i,i*i ) while i < 5:
print( i,i*i )
i=i+1
>>> >>>
0 0 0 0
1 1 1 1
2 4 2 4
3 9 3 9
4 16 4 16
Function
Function
def Grade(marks):
if marks >= 90:
grade=’Ex’
elif marks >= 80:
grade=’A’
elif marks >= 70:
grade=’B’
elif marks >= 60:
grade=’C’
elif marks >= 50:
grade=’D’
elif marks >= 35:
grade=’P’
else:
grade=’F’
return grade
Class
Class
from math import sqrt
class Triangle(object):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
def area(self):
s=0.5*(self.a+self.b+self.c)
A=sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
return A
A=Triangle(a=3,b=4,c=5)
print ( A.area() )
Class
class Triangle(object):
def __init__(self,**kwargs):
for key, value in kwargs.items():
vars(self)[key]=value
def area(self):
s=0.5*(self.a+self.b+self.c)
A=sqrt(s*(s-self.a)*(s-self.b)*(s-self.c))
return A
A=Triangle(a=3,b=4,c=5)
print ( A.area() )
Class
Check function arguments
class Triangle(object):
def __init__(self,a,b,c):
self.a=a
self.b=b
self.c=c
Usage of **kwargs as function arguments
class Triangle(object):
def __init__(self,**kwargs):
for key, value in kwargs.items():
vars(self)[key]=value
Module
Module
A module is a file consisting of Python code.
A module can define functions, classes and variables.
Input/Output
Reading from a file
File:test.dat
1 0.0 0.0 0.0
2 5.0 0.0 0.0
3 5.0 4.0 0.0
Python code for reading from file ’test.dat’
with open(’test.dat’,’r’) as datafile:
for line in datafile:
nums=line.split()
nid=nums[0]
x=nums[1]
y=nums[2]
z=nums[3]
print ( nid,x,y,z )
Reading from ’test.dat’ and writing in ’test.out’
fout=open(’test.out’,’w’)
with open(’test.dat’,’r’) as datafile:
for line in datafile:
nums=line.split()
nid=int(nums[0])
x=float(nums[1])
y=float(nums[2])
z=float(nums[3])
print ( nid,x,y,z )
fout.write(’%3d %8.3f %8.3f %8.3f\n’%(nid,x,y,z))
fout.close()
How Python is Compiled?
How Python is Compiled?
Lexer -> token stream
Uses a stack to parse whitespace!
Parser -> concrete syntax tree
Simple & LL(1) parsing engine
Filter -> abstract syntax tree (uses ASDL)
Pass 1 -> symbol table
Pass 2 -> bytecode
Bytecode is in-memory objects
Saving to disk (.pyc file) is just a speed hack
> (from the presentation of Guido van Rossum, Creator of Python)
How Python is Executed?
How Python is Executed?
Virtual machine executes bytecode
Simple stack machine
Stack frames allocated on the heap
C stack frames point to heap stack frames
Additional stack for try blocks
VM calls out to "abstract" operations
Some bytecodes represent "support" calls
> (from the presentation of Guido van Rossum, Creator of Python)
Let’s hear from Guido van Rossum : Creator of
Python
Let’s hear from Guido van Rossum : Creator of
Python
For the beginner:
easy-to-learn syntax,
easy-to-use data structures,
and an interactive interpreter that’s open to experimentation.
Also a large set of readable examples in the form of the standard
library,
a friendly community that’s eager to answer questions,
good free on-line tutorials, and plenty of books to learn from.
Let’s hear from Guido van Rossum : Creator of
Python
For the pro:
a large standard library and
an even larger library of third party add-on modules and packages,
exceptions, several layers of programming structuring devices
(packages, modules, classes),
a choice of several different GUI toolkits, and
the ability to write your own extension modules in C, C++ or
Fortran.
Let’s hear from Guido van Rossum : Creator of
Python
For the casual programmer:
a syntax that’s easy to remember,
a large standard library with pre-built solutions,
a vast amount of documentation, and
real power under the hood when you need it.
Try It Out!
Try it out!
Download Python from www.python.org
Any version will do
By and large they are all mutually compatible
Recommended version: 2.7
Use VIDLE if you can
Download numpy, scipy, matplotlib, vtk, vis
Please note: Python 2 are not maintained past 2020
Try It Out!
Try Python 3
using Spyder or Jupyter Notebook under Anaconda 3
Spyder 3
Spyder 3
Jupyter
Python 3
Download Python from www.python.org
Any version will do
Recommended version: 3.7
Use IDLE for integrated development environment (IDE)
Download numpy, scipy, matplotlib, pylatex, vtk, pandas, django
How to install packages
pip is the package installer for Python
For example, to install matplotlib, use
D:\> pip install matplotlib
To upgrade pip, use
D:\> python -m pip install --upgrade pip
If Python is not in the path, to install matplotlib, use
C:\Python37\Scripts> pip install matplotlib
If Python is not in the path, to upgrade pip, use
C:\Python37> python -m pip install --upgrade pip
Very Very Important!
Do not use file name as ’string.py’
Do not use file name as ’matplotlib.py’
In other words, do not use the same name as your import name
You will get import error and will struggle for days to find the
solution.
Summary
Summary
No type checking in the compiler
Dynamic typing, static scoping
Everything is an object
Everything has a namespace
Everything can be introspected, printed
Simplicity of implementation
Open source, free and cross-platform
References
References
Python for Scientists, John M. Stewart, Cambridge University
Press, 2014
Programming Python, Mark Lutz, O’Reilly,2012