Python Basics¶

Stats 507, Fall 2021

James Henderson, PhD
September 2, 2021

Overview¶

  • Semantics
  • (Strong) scalar types
  • Indentation
  • Functions
  • Object Oriented
  • Takeaways

Interpreted¶

  • Python is an interpreted language.
  • This aids in interactive exploration.
  • But also means the order in which you run code (cells) matters.

Assignment¶

  • Assign named variables to values (objects) using =.
  • We also say the variable name is bound to its value.
In [ ]:
x = 42
instructor = 'Dr. Henderson'
pi = 3.14
yeti = False

Assignment¶

  • Assignment uses dynamic referencing.
  • The type/class is determined from the value, not declared.
  • Type/class information belongs to the data, not the name bound to that data.

Aliasing¶

  • When we assign one variable to another, we do not (usually) copy the associated data.
  • Instead we simply bind a new name to the same instance or location in memory.
  • The two variables are said to be aliased.
  • Primarily important for mutable classes.

Aliasing¶

  • Here is an example using the mutable list class.
In [ ]:
x = [42]; y = x; x.append('Jackie Robinson')
print(y)
y.append('Mariano Rivera')
print(x)

Aliasing¶

  • Test if two variables are aliased using is.
  • Use a mutable object's .copy() method to copy its values to a new location.
In [ ]:
print(x is y)
x = [42]
y = x.copy()
print(x is y)
x.append('Jackie Robinson')
print(y)

Scalar Types¶

  • Python has several "scalar" types in its built-in library: int, float, str, bool, None, bytes.
  • Other types are defined in external libraries such as Numpy.
  • Cast between (some) types using functions of the same name.
  • Scalars are immutable.
In [ ]:
x = 5e-1
print(float(x))
print(str(x))
print(bool(x))
print(bool(int(x)))

Scalar Types¶

  • Check if a variable is of a particular type using isinstance().
In [ ]:
x = 5e100
print(isinstance(x, float))
print(isinstance(x, int))

Numeric Types¶

  • Python's integer type int can hold arbitrarily large integers.
  • The float type is a double-precision (64-bit) floating point number.
  • Do math with (arithmetic) binary operators: +, -, *, /, //, %, **.
  • Floating point arithmetic is approximate.
In [ ]:
print(13 / 2)  # thanks Python 3
print(13 // 2) # integer divsion
print(13 % 2)  # mod
x = 2 ** 0.5
print(x ** 2 - 2)

Boolean types¶

  • The bool type holds logical values.
  • In Python, these are True and False.
  • Comparison operators return type bool.
  • Boolean operators act on and return type bool.
In [ ]:
eps1 = 1e-8
eps2 = 1e-16
z = (2 ** 0.5) ** 2 - 2
b1 = z < eps1
b2 = z > eps2
b1 and b2

Ternary expressions¶

  • Python supports ternary (three-part) expressions in boolean operations.
  • Will reappear elswehere, e.g. conditional execution.
In [ ]:
print((eps1 > z) and (z > eps2))
eps2 < z < eps1

String types¶

  • Python's built in string type is flexible and has a number of associated methods.
  • One especially useful method is .format().
In [ ]:
x = 42; n = 100
phat = x / n
se = (phat * (1 - phat) / n) ** 0.5
lwr, upr = phat - 1.96 * se, phat + 1.96 * se
ci_str = "{0:.1f}% (95% CI: {1:.0f}-{2:.0f}%)"
pretty = ci_str.format(100 * phat, 100 * lwr, 100 * upr)
pretty

Format Example¶

  • Can also use the prefix f for a "glue" like syntax.
In [ ]:
from IPython.display import Markdown
Markdown(f'''
 > Life is {pretty} towels.
 >
 > --Unknown. 
 ''')

Strong types¶

- Python is strongly-typed ...¶

In [ ]:
try:
    5 + 'phi' 
except: 
    print('Error')

Strong types¶

  • Python is strongly-typed ...
  • ... though float and int types play nicely.
In [ ]:
n = 5; phi = (1 + 5 ** 5e-1) / 2
print(isinstance(n, int))
print(isinstance(phi, float))
print(n * phi)

Indentation¶

  • Python uses indentation to structure code ...
  • ... unlike many other languages, e.g. R, C++, which use braces `{}`.

  • In Python, indentation is functional, not just good style.

Indentation¶

  • Functional whitespace makes python more readable to humans ...
  • ... but also potentially harder to debug (in the beginning).

Indentation¶

  • Limit difficulties by following the convention of indenting with 4 spaces.
  • Avoid tabs, `\t`, but use the tab key when your editor is enabled to translate.

Indentation¶

  • A colon : is used to denote the start of an indented block.
In [ ]:
k = 0
for i in range(10):
    k += i
print(k)

Functions¶

  • Recognize function calls by () after the function name.
  • Functions take 0 or more arguments.
  • Some arguments are required, others have default values and can be omitted.
In [ ]:
print(round(3.141592653589793))
print(round(3.141592653589793, ndigits = 1))

Functions¶

  • Agruments can be passed by position or keyword. Use position for the most common arguments, and keywords otherwise.
  • Positional arguments must precede keyword arguments.
In [ ]:
print(round(3.141592653589793, ndigits=2))
print(round(3.141592653589793, 3))
# error
# round(digits = 2, 3.141592653589793)

Functions¶

  • ... are one of the most useful programming contructions.

  • ... allow you to name and reuse blocks of code.

  • ... help you to break complex problems into simpler parts.

  • ... make your code more readable.

  • Rule of thumb: if you copy-and-paste the same code more than once, it's probably better to encapsulate that code into a function.

Functions¶

  • Use the def keyword to define a new function.
In [ ]:
def n_vowels(s):
    n = 0
    for v in ['a', 'e', 'i', 'o', 'u']:
        n += s.count(v)
    return(n)

Functions¶

  • Include a docstring on all named functions.
  • Here's a template from Spyder - use this template every time.
In [ ]:
def s(x, y = 0):
    """
    Describe your function's purpose concisely. 

    Parameters
    ----------
    x : TYPE
        DESCRIPTION.
    y : TYPE, optional
      DESCRIPTION. The default is 0.

     Returns
     -------
     None.

    """

Python is Object-Oriented¶

  • Everything in Python is an object.
  • Objects are instances of a class with internal data and (usually) associated methods.
  • Methods are functions that belong to objects and have access to associated data.

Method Calls¶

  • Method calls take the form object.method().
  • Here we create an object book of class str ...
  • ... and then call its title() method.
In [ ]:
book = "the hitchhiker's guide to the galaxy"
print(book.title())

Takeaways¶

  • Python is an interpreted, strongly-typed language that uses dynamic references.
  • Hierarchy is denoted using indentation(!) with : denoting the start of an indented block.
  • Python is object-oriented. Use methods, but follow a functional programming style.
  • Use functions to keep DRY (and don't forget the docstring).