Open Educational Resources

Python Tutorial with YOLO Implementation: Quick Introduction to Python

1.0 Google Colab

All my examples below will be using Google Colab. Google Colab is a cloud version of Jupyter Notebook, consisting of HTML code and Python3 code. You can also use other coding languages, but we will just focus on Python3.

To get started, go to your google drive, select new -> more -> Google Colabatory. Note that the file type is a “ipynb”, so you can also import Jupyter Notebooks from your computer.

Colab supports two types of blocks: HTML code (Text), and Python3 code(Code). To create a new block, click on the Code or Text button found either near the top of the page, or below a created block.

To edit the contents of the Text code, double click. There are a bunch of functions you can used within the text code:

  • # <header name> Header 1
  • ## <header name> Header 2
  • *<word>* Italic
  • **<word>** Bold
  • – <item> List

You can also insert images, and add hyperlinks.

To run the Code block, there will be a play button when you hover over the runtime value. The runtime value tells you when that block was exucuted. If it is blank, then it has not been executed. You can also run the block simply with the shortcut “CTRL + ENTER”.

One more thing to note are the runtime settings.

  1. Restart runtime – restarts the notebook and clears all variables
  2. Factory Reset Runtime – restarts the notebook and clears all variables and all imported files
  3. Run all – run all cells sequentially

Installing and Upgrading Libraries

While Colab has many pre-installed libraries, any additional libraries must be installed using !pip install <library name>

Some features may only available in newer versions of a library and so upgrading a library may be necessary. Run !pip install <library name> --upgrade and then Restart Runtime

!pip install matplotlib                 # To install 
!pip install matplotlib --upgrade       # To upgrade

Comments

Comments are lines of code preceded by a hashtag(‘#’). They do not execute and are used for giving more information to the code.

# This is a comment

Print command: 

A function that displays the output. Multiple values can be printed on the same line by separating them by commas.

print("Hello World")    # Hello World
print("Hello", "World") # Hello World
print(10)               # 10
print(20.1)             # 20.1
print(1 + 1)            # 2
print(1,2,3)            # 1 2 3

Input command:

Gets an input from the user. Press ‘enter’ to put in the input.

print("What is your name?")    
print("Hello", input())        # input() is used here. 

For the example above, it first prints the first line. It does not print the second line yet since the 2nd line of code requires the user’s input, so getting the input will be first, and then it will print the 2nd line. You can also save “input() into a variable(discussed below) to be used later.

Variables

Variables help store values to be used later. Every variable in Python is defined by class, specifically a type. Some common types are:
integers, floats, booleans, strings.

Integers

Integers are whole numbers. They can be used to numerically calculate other integers.

Floats

Floats are sometimes defined as double in other programming languages. Floats are numbers with decimals. They can be used to numerically calculate integers and other floats.

Booleans

Booleans are use in boolean logic to produce only two outputs. Those are “True” or “False”.

Strings

Strings are a sequence of characters. In python, Strings are surrounded by either single quotation marks or double quotation marks. For style, you just want to keep it consistent so it is more readable. Strings can be combined together using the ‘+’ operation.

a = 1                                    # Integer class
b = 0.5                                  # Float class
c = True;                                # Boolean class
d = "This is a string"                   # String class

Naming Variables:

Officially, variables names in Python can be any length and can consist of uppercase and lower case letters (a-zA-Z), digits (0-9), and the underscore character (‘_’). Note: One constraint is that the first character of the variable cannot be a digit.

NOTE: They are also keywords that you cannot name such as “and”, “as”. Here is a link to all the keywords.

For style, if the variable has multiple words, you would want to add an uppercase for the next word (Style 1) or add an underscore separating the words as shown below (Style 2).

bigNumber1 = 3 ** 8       # Style 1
big_number_2 = 2 ** 10    # Style 2
big_Number_3 = 4 ** 12    # Mix of both styles
Casting Variables:

You can cast variable types into other variable types.

a = 3.1        # This is a type double
print(int(a))  # Prints an integer
Chaining Variables

Chaining variables make it so you can assign multiple variables to one value.

a = b = 1   # 'a' and 'b' are assigned to 1
b = 2       # 'b' now is 2, 'a' is the same
More Examples
String functions

Here’s how to combine strings, as well as splitting strings into a list (discussed in 1.5).
More functions can be found here.

a = "Hello"                # String 1
b = "there"                # String 2
c = a + ", " + b           # Combining Strings
d = c.split(",")           # Splitting the string by each ", " 
Strings with white-space characters

Here are some white-space characters.

print("Hello \tWorld")      # Tab using '\t'
print("hello \nworld")      # Newline using '\n'

Data Structures:

These are used to contain one or more contents of variables. Generally, data structures will have an element and an index. The element is the value stored, and the index is the position of where the element is in the data structure.

A few data structures in python are lists, tuples, sets, dictionaries. We will mainly be focusing on lists.

A list is a sequence of values that are sorted in order. The first element in a list is indexed at 0. There are a bunch of function for using the class lists such as:

  • Creating empty list
  • Creating non-empty list
  • Length of list
  • Add element to the end
  • Add element at index
  • Access element at index

Note: There are more functions for lists, this is just naming a few. Here is a link for more.

mylist = []                  # Empty list             
mylist = [1, 2, 3]           # Non-empty list             
mylist = [1, 2.1, "hello"]
print(len(mylist))           # Length
mylist.append(7)             # Append
mylist.insert(2,"var")       # Insert(index, value)
print(mylist[0])             # Get index
mylist = [[1, 2, 3], 
          ["a", "b", "c"], 
          ["!", "@", "#"]]   # Nested list             
print(mylist[0][1]) 
Tuples

Tuples are similar to lists in that it is in order, and they allow duplicates. The only difference is once a tuple is made, it cannot be changed. They are stored using “()” brackets.

Sets

Sets are unordered and unindexed. They are stored using “{}” brackets.

Dictionaries

Dictionaries are unordered with using a key for the index and a value for the elements. A key cannot be duplicated
They are stored using “{key: value}” brackets with a colon to separate the key and value.

Tuple Example:
a = ("apples", "oranges", "banana")     # Cannot change contents
Set Example:
a = {1, 2, 3, 3}        # a = {1, 2, 3}
Dictionary Example:
a = {"Name" : "John", 
     1 : 40, 
     "Age" : 20}

Operators:

There are a bunch of math arithmetic functions already built into python. Here is a list of these.

  • Addition
  • Subtraction
  • Division
  • Integer Division
  • Remainder(mod)
  • Exponent
  • Round to Integer
  • Round to n Decimal Places
  • Absolute Value
#Operations with integers and floats
print("Addition:", 5 + 3)              # Add 5 + 3 = 8
print("Subtraction:", 5 - 3)           # Sub 5 - 3 = 2
print("Multiplication:", 5 * 3)        # Mul 5 * 3 = 15
print("Division:", 5 / 3)              # Div 5 / 3 = 1.66...
print("Integer Division:", 5 // 3)     # IntDiv 5 // 3 = 1
print("Remainder:", 5 % 3)             # Mod 5 % 3 = 2
print("Exponent:", 5 ** 3)             # Exp 5 ^ 3 = 125
print("Round:", round(3.1415))         # Round 3.1415 = 3
print("Round:", round(3.1415,2))       # Round to 2 dec 3.1415 = 3.14
print("Absolute Value:", abs(-10))     # Abs of -10 = 10

Comparisons:

These are used to evaluated expressions to either true or false. These expressions are generally used in if-else statements and loops. Note: You can nest expressions to make more complicated expressions.

  • ‘==’   Compares two values. Returns true if they are equal.
  • ‘>’   Returns true if the value on the left is greater than the right.
  • ‘<‘   Returns true if the value on the left is less than the right.
  • ‘>=’   Returns true if the value on the left is greater or equal to the right.
  • ‘<=’   Returns true if the value on the left is less than or equal to the right.
  • ‘!=’   Compares two values. Returns true if they are not equal.
  • ‘not()’   Returns true if the compare expression is false. ( Wrong in the video)
  • ‘and’   Returns true if the right and the left are both True
  • ‘or’   Returns true if either the right or the left is True
print("i" == "i")               # True
print("4 > 5:",4 > 5)           # False
print(2 <= 3)                   # True
print(2 != 1)                   # True
a = 1
b = 1
print(a == b)                   # True
x = 0
print(x > -1 and x < 1)         # True

If statement

An if statement creates a decision structure, allowing a program to have more than one path of execution.
It causes one or more statements to execute only when an expression is True.

If-else statement

An if-else statement adds the ability to conditionally execute code when the if condition is false.

Else statement

An else statement executes if all conditions are false.
Note: If-Else and Else’s statements are not required.

Nested if statements

You can next if statements within if statements.

NOTE: The indented code after an if statement(or else) is the block of code that will be executed if the statement is conditionally true. Indented code is also used in the later examples such as loops and defined functions.

Example 1:
if(True):                   # The condition evaluated to true
    print("This is True")
else:
    print("This is False")  # Skips since if is True
Example 2:
x = 2
if x == 1:                  # 'x' is not 1
    print("x is 1")
elif x == 2:                # 'x' is 2 so the code executes
    print("x is 2")
else:
    print("x is something else")
Example 3:
#Examaple of nested if statement
x = [2,3]
y = 3
if 2 in x and len(x) == 2:
    if y == 3:
        print("This is true")      # This here is executed
    else:
        print("This is False")
else:
    print("This is False")

Loops

A loop is a way to repeat an action (or a set of actions) without writing the same code over and over.

For Function

For function is a type of loop that you know how many times you want to repeat the code or iterate through a list.

Iterate Function

A type of for loop. You can iterate through a data structure(e.g list), as well as strings, using ‘in’.

Range Function

The range function can create a sequence of integers. It has three parameters, start (default 0), stop, step(default 1).

Example 1:
# Iterate Function
print("Print List")  
a = [1, 2, 3, 4, 5, 5]    # list
for i in a:               # 'i' is the object iterating in list
    print(i)
print("Print String")
a = "Hello World"         # String
for i in a:               # 'i' is the character iterating in string 
    print(i)
Example 2:
# Range Function
print("Start 2, end 10, step 3")
for a in range(2, 10, 3):          # range(start, end, step)
    print(a)
print("start -4, end 2")
for a in range(-4, 2):             # range(start, end), step = 1
    print(a)
print("end 5")
for a in range(5):                 # range(end), start = 0, step = 1
    print(a)

While Function

While function is a type of loop that you do not know how many times it will repeat. It is condition controlled.

Note: beware of infinite loops. Make sure you can break the loop or else the function will never exit.

x = 5                 # 'x' starts at 5
while x > 1:          # While true it will loop
    print(x)
    x = x - 1         # Decrements 'x'

Own Defined Functions

You can defined your own functions using “def functionName()”:
You can also add parameters to use in the function inside the round brackets. They can have default values but those values can only be determined after generating non-default values. They can also have return values. If the function does not have a return value, it returns ‘none’.
Note: you have to generate a main function for the file to run in order to define other functions.

Example 1:
def say():                    # Defined function
    print("Hello there.")
def ask():                    # Another defined function
    print("How are you?")
if __name__ == "__main__":    # Main function
    say()                     # Call defined function
Example 2:
# a has a non-default value, b and c does
def say(a, b = "How are you", c = "How you been"):   
    print(a)
    print(b)
if __name__ == "__main__":
    print("Say:")
    say("Hello")                                    # One parameter
    print("Say:")
    say("Hi there.", "What's up.")                  # Two parameters
Example 3:
# 'a' and 'b' are placeholder variables for the function
def add(a, b):                    
    return a + b
if __name__ == "__main__":
    c = 3
    d = -4
    # Uses our defined function above calculating 'c' and 'd'
    print("c + d =", add(c,d))

Modules

You can add modules to use their library function that is not built into python originally, you can also access another file that you have created. The example below uses the ‘random’ module. Link to doc

# 'ran' is called in place of 'random' with use of 'as'
import random as ran                               
for a in range(5):
    # randrange is a function from random module
    print("random number: ", ran.randrange(0,10))

References

Link to Weichen Qui’s python lab tutorial for the numerical analysis courses.

Link to Weichen Qui’s python lab tutorial video.

Leave a Reply

Your email address will not be published.