Intro To Python Part 1
Intro To Python Part 1
Part 1
v0.7
There is documentation for using Python on the SCC on the RCS website.
Use the module system to find Python:
Getting Python for Yourself: Anaconda
Pros:
Faster development
Easier debugging!
Helps organize code
Increased efficiency
Cons
Learning curve
Can add complexity to smaller
problems
The Spyder IDE
file editor
Python console
Tutorial Outline – Part 1
What is Python?
Operators
Variables
Functions
Classes
If / Else
Tutorial Outline – Part 2
Lists
Tuples and dictionaries
Modules
numpy and matplotlib modules
Script setup
Development notes
Tutorial Outline – Part 1
What is Python?
Operators
Variables
Functions
Classes
If / Else
What is Python?
Python…
…is a general purpose interpreted programming language.
…is a language that supports multiple approaches to software design,
principally structured and object-oriented programming.
…provides automatic memory management and garbage collection
…is extensible
…is dynamically typed.
By the end of the tutorial you will understand all of these terms.
Some History
“Over six years ago, in December 1989, I was looking for a "hobby"
programming project that would keep me occupied during the week
around Christmas…I chose Python as a working title for the project, being
in a slightly irreverent mood (and a big fan of Monty Python's Flying
Circus).”
–Python creator Guido Van Rossum, from the foreward to Programming Python (1st ed.)
Goals:
An easy and intuitive language just as powerful as major competitors
Open source, so anyone can contribute to its development
Code that is as understandable as plain English
Suitability for everyday tasks, allowing for short development times
Compiled Languages (ex. C++ or Fortran)
Interpreted Languages (ex. Python or R)
python prog.py
A lot less work is done to get a program to start running compared with compiled
languages!
Python programs start running immediately – no waiting for the compiler to finish.
Bytecodes are an internal representation of the text program that can be efficiently run by
the Python interpreter.
The interpreter itself is written in C and is a compiled program.
Comparison
IPython adds some handy behavior around the standard Python prompt.
Tutorial Outline – Part 1
What is Python?
Operators
Variables
Functions
Classes
If / Else
Operators
Python supports a wide variety of operators which act like functions, i.e.
they do something and return a value:
Arithmetic: + - * / % **
Logical: and or not
Comparison: > < >= <= != ==
Assignment: =
Bitwise: & | ~ ^ >> <<
Identity: is is not
Membership: in not in
Try Python as a calculator
+ - * / % ** == ( )
What is Python?
Operators
Variables
Functions
Classes
If / Else
Variables
Variables refer to a value stored in memory and are created when first
assigned
Variable names:
Must begin with a letter (a - z, A - Z) or underscore _
Other characters can be letters, numbers or _
Are case sensitive: capitalization counts!
Can be any reasonable length
Assignment can be done en masse:
x = y = z = 1
Try these out!
Multiple assignments can be done on one line:
x, y, z = 1, 2.39, 'cat'
Variable Data Types
The type is identified when the program runs, using dynamic typing
Compare with compiled languages like C++ or Fortran, where types are identified by
the programmer and by the compiler before the program is run.
Run-time typing is very convenient and helps with rapid code development
31
Strings
Strings are a basic data type in Python.
32
Tutorial Outline – Part 1
What is Python?
Operators
Variables
Functions
Classes
If / Else
Functions
Functions are used to create pieces of code that can be used in a
program or in many programs.
Programs that make heavy use of function definitions tend to be easier to:
develop
debug
maintain
understand
Function name
Python functions Optional comma-separated
list of arguments (incoming
variables)
Keyword def
A code block
In Spyder’s editor:
Define a function called mathcalc that takes 3 numbers as arguments and returns
their sum divided by their product.
Save the file, run it, and then call it from the console:
def mean(x,y,z):
Another code block return (x + y + z) / 3.0
def my_func(a,b,c=10,d=-1):
…some code…
If you are having trouble with memory usage contact RCS for help or take
the Python Optimization tutorial to learn more.
Tutorial Outline – Part 1
What is Python?
Operators
Variables
Functions
Classes
If / Else
Classes
In OOP a class is a data structure that combines data with functions that
operate on that data.
Population 685094
def has_4_0(self):
return self.gpa==4.0
me = Student("RCS Instructor","U0000000",2.9)
print(me.has_4_0())
radius = 14.0
width_square = 14.0
a1 = AreaOfCircle(radius) # ok
a2 = AreaOfSquare(width_square) # ok
a3 = AreaOfCircle(width_square) # !! OOPS
If we defined Circle and Rectangle classes with their own area() methods…it is not
possible to miscalculate.
# create a Circle object with the radius value
c1 = Circle(radius)
r1 = Square(width_square)
a1 = c1.area()
a2 = r1.area()
When to use your own class
A class works best when you’ve done some planning and design work
before starting your program.
This is a topic that is best tackled after you’re comfortable with solving
programming problems with Python.
W3Schools: https://www.w3schools.com/python/python_classes.asp
A variety of methods (functions) accessible once you have a string object in memory.
You can’t access string functions without a string – in Python the string
provides its own functions.
No “strcat” / “strcmp” / etc as in C
No “strlength” / “isletter” / etc as in Matlab
No “nchar” / “toupper” /etc as in R
String functions
In the Python console, create a string variable
called mystr
mystr.upper()
mystr.isdecimal()
help(mystr.title)
The len() function
It’ll return the length of any Python object that contains any
countable thing.
len(mystr) 6
+ concatenates strings.
+= appends strings.
These are defined in the string class as functions that
operate on strings.
What is Python?
Operators
Variables
Functions
Classes
If / Else
If / Else
If, elif, and else statements are used to implement conditional program
behavior
Syntax: if Boolean_value:
…some code
elif Boolean_value:
…some other code
else:
…more code
elif and else are not required – use them to chain together multiple
conditional statements or provide a default case.
Try out something like this in the Spyder
editor.
EXCEPT when typing code into the Python console. There an empty line
indicates the end of a code block.
This sometimes causes confusion when pasting code into the console.
Solution: try to avoid pasting more than a few lines into the Python console.