Knowledge Base

1. Python: Structure, Syntax, Definitions

1.1. Types of Variables

  1. Local variables are declared and exist inside of functions. These are temporary variables that exist to perform operations inside of a function. After the function completes, local variables no longer exist and cannot be referenced later.
  2. Global variables are declared and exist outside of functions. These are variables in the main code that can be accessed at any time. Note: they cannot be accessed inside of a function unless they are passed in as an argument.

Variable names are case sensitive and cannot start with numbers.

1.2 Datatypes

A variable’s datatype determines the amount of computer memory needed to store the data and the types of operations that can be done to the data.

Common datatypes

  • str
    • text data
    • var = "Hello Word"
  • int
    • integer values (no decimal places)
    • var = 10
  • float
    • floating-point numbers (decimal places)
    • var = 3.14
  • bool
    • logical
    • True or False

Python automatically determines the datatype of a variable. Use the built-in function type() to print a variables datatype (See section 2).

1.3. Data Structures

Data structures are ways of organizing and storing data such that operations can be done more efficiently.

Common data structures

1. List

A list is a collection of items. Each item in a list is referred to as an element. The elements in a list can be of different datatypes and contain duplicates making the list very versatile.

To create a list, place all elements inside square brackets and separate each element with a comma. For example:

1customer_info = ['Male', 35, '555 Fake St', 105.59']

creates a list of text and numeric data for some customer.

To create a nested list, define a list whose elements are list. For example:

1customers_info = [
2 ['Male', 35, '555 Fake St', 105.59'],
3 ['Female', 32, '321 Go Get Em St', 199.59']
4]

creates a nested list representing two customers.

2. Dictionaries

A dictionary in Python is a collection of values that are accessed with a key. The values can be of any datatype, but keys must be immutable objects (section 1.4.1. below) such as strings. Keys must be unique and can only be associated with one value.

To create a dictionary, place all key-value pairs inside curly brackets separated with commas and separate keys and values with colons. For example, Run_Times = {'8ea978' : 30.58, '9gf471' : 28.95, '3sf857' : 35.89} creates a dictionary of race time data where the key is the six-character bib number and the value is the race time.

3. DataFrames

DataFrames store data in rows and columns. Each column represents a variable and can be of different datatypes. Each row is associated with an index value that can be numeric or character values. Typically, each row contains data corresponding to a unique sampling unit (e.g., a person, house, location, etc.).

1.4 Objects and Classes

Python is an object orientated programming language, meaning everything in Python can be viewed as an object including variables you create. Every object belongs to a class. The class of an object defines the objects properties and available methods (see section 3 for a list of methods per class).

Python automatically determines a variable’s object and class. If you create the variable tmp = [1,2,3,'on','off'], Python will recognize this as a list object and all methods of the list class will be automatically available. (see section 3.2)

Objects have properties associated with them. Below are two important properties.

1. Mutable vs Immutable Objects

Mutable objects can be changed without redefining the variable; immutable objects cannot.

Example: String objects are immutable. Trying to change the string object text from “mouse” to “house” using text[0] = 'h' will cause an error. Instead, you must redefine text with text = 'house'.

List objects are mutable. We can change the first element of a list to 'h' using list[0] = 'h' without any problems.

2. Iterable Objects

Iterable objects are capable of returning their components one at a time. You can loop over iterable objects such as list or dict or str. You cannot loop over non-iterable objects such as int or float.

For example, the string text = "Hello World" is iterable. You can return the letters "H", "e", "l", etc. using a loop or by indexing.

The int object num = 12345678 is not iterable. You cannot loop over or index the individual numbers in num.

1.5. Augmented Assignment

A shorthand notation used when applying an arithmetic operator on a variable while saving the results to the same variable. Below are examples for the operators +, -, *, /.

1var= 1 # var must exist before the below can run
2
3# augmented assignment examples
4var += 2 # same as var = var + 2
5var -= 2 # same as var = var - 2
6var *= 2 # same as var = var * 2
7var /= 2 # same as var = var / 2

1.6. Methods and Functions

1.6.1. Parameters and Arguments

Parameter: a variable inside a function or method. During runtime, parameters are replaced by either default values or input arguments specified by the user.

Argument: a value passed to a function.

1.6.2. Functions

Built-in functions are written by Python developers and are not associated with a library.

User-defined functions are written by users to make code more readable and reliable.

To call a function, type the function name followed by any arguments written inside parentheses. Example: sorted(list_obj).

See section 2 for a list of built-in functions

See section 7 for how to write a user-defined function

1.6.3. Methods

Methods are functions that are associated with specific objects and typically operate on the object they are called on. To call a method, type the object you want to call it on, followed by a dot and the method name. Example: list_obj.sort().

See section 3 for list of methods per object class.

1.7. Libraries

A Python library is a collection of functions/methods written by members of the Python community.

A library is loaded with the import command and can be assigned an alias with as. Aliases simplify code and reduce the amount of typing.

Example: the code below loads the pandas library and assigns it the alias pd.

1import pandas as pd

1.8. Errors and Try-Except

When errors in code are encountered, the Python program terminates and an error message is displayed. Error messages provide information as to the reason for the error.

Below are errors messages you've already encountered:

  • ZeroDivisionError - can’t divide by zero
  • TypeError - can’t perform the desired operation on the current datatype
  • IndexError - can’t access the desired index. The indexed variable doesn’t exist or is invalid
  • KeyError - dictionary key does not exist
  • IndentationError - spaces or tabs in code are not placed correctly (Python uses four spaces to register code blocks)

try-except blocks provide a syntax to test code for errors without the risk of the program terminating. The syntax is

1try:
2 # Code A: code to test
3except:
4 # Code B: code to run if code A errors

The code after try and after except must be indented with 4 spaces.

Send Feedback
close
  • Bug
  • Improvement
  • Feature
Send Feedback
,