Logic

Dr. Huidae Cho
Institute for Environmental and Spatial Analysis...University of North Georgia

1   Logical flows

Logical flows in programming are top-down, not bottom-up. For example,

x is 1
x is 10

What is x? x was initially 1, but it was overwritten by 10 later. x is 10 at the end of the code.

2   Logical blocks

Think about this. It’s not Python in any way, but I’m talking about logic.

If you’re an IESA student:
    You know how to use GIS
    You should have an ArcGIS online account
    Set you’re ready
Else:
    Let me know; I’ll create you a new ArcGIS online account
    Set you’re not ready

Did you understand the above if-else statement? Are you ready or not ready?

For each of you in this class:
    If you are familiar with programming
        Learning Python shouldn’t be too difficult
        Say “Great!”
        You’re comfortable with programming
    Else:
        Learning programming for the first time
        Say “OK”
        You’re not comfortable with programming

Did you get this logical structure? What did you say and are you comfortable with programming or not? Let’s try this:

Total is 0
For x in 1, 2, and 3:
    Add x to total

What is total now? Again, don’t try to run this in Python. It’s not Python. I’m testing your logical thinking skills.

Total is 0
For x in 1, 2, and 3:
    Add x to total
    Add 1 to total

Now, what is total?

What about this?

Total is 0
For x in 1, 2, and 3:
    Add 1 to total
    Add x to total

Please try all these questions. These are very basic constructs of logic.

Have you all noticed indentation? Yes, indentation is used to create logical blocks. Any consistent indentation after “if” or “for” before a deindented “else” or unindented expression creates a group of actions. For example,

Set x to 1
If x is 1:
    y = 2
    z = 3
Else:
    y = 20
    z = 30

What are y and z? Yes, y is 2 and z is 3 because “x is 1” is True. What if x was 2? Then “x is 1” would be False and y and z would then be 20 and 30, respectively. Can you interpret this if-else construct? Here, there are two logical blocks:

    y = 2
    z = 3

and

    y = 20
    z = 30

3   If-else

An “if-else” construct is used to create branches. A branch splits the workflow into two: one for True conditions and the other for False conditions. For example,

If True:
    You will only hit this code block
    because the conditional statement after "if" is
    always True
Else:
    You will never hit this code block
    because it is run only if the above
    "if" conditional statement fails,
    but True will never fail

4   Loops

4.1   For loops

Let’s take a look at a “for” construct.

y = 0
For x in 1, 2, and 3:
    Add x to y

What is y now? Let me unroll this “for loop” (yes, we call it a loop because “Add x to y” repeats for three x values: 1, 2, and 3).

y = 0

x = 1
Add x to y

x = 2
Add x to y

x = 3
Add x to y

What is y? Let me further expand this logic:

y = 0

x = 1
Add 1 to y because x is 1
Now y is 1 because adding 1 to 0 (y was 0 right?) yields 1

x = 2
Add 2 to y because x is 2
Now y is 3 because adding 2 to 1 (y was 1 above right?) yields 3

x = 3
Add 3 to y because x is 3
Now y is 6 because adding 3 to 3 (y was 3 above right?) yields 6

Yes, y is 6.

4.2   While loops

What does this code do?

x = 0
n = 3
While n > 0:
    Add n to x
    Subtract 1 from n

What is x?

Let me expand the above “while” loop. From now on, any statements after a hash sign (#) are comments to explain near-by code, not part of the program.

x = 0
n = 3

If n <= 0:  # False because 3 is not <= (less than or equal to) 0
    Stop

Add n to x
n = n - 1   # n is now 2

If n <= 0:  # False because 2 is not <= 0
    Stop

Add n to x
n = n - 1   # n is now 1

If n <= 0:  # False because 1 is not <= 0
    Stop

Add n to x
n = n - 1   # n is now 0

If n <= 0:  # True because 0 is <= 0
    Stop    # stop the program

Guess what x is. Let me expand it more:

x = 0
n = 3

If 3 <= 0:  # False
    Stop

Add 3 to x  # x was 0 and adding 3 to x yields x = 3
n = 3 - 1   # n is now 2

If 2 <= 0:  # False
    Stop

Add 2 to x  # x was 3 and adding 2 to x yields x = 5
n = 2 - 1   # n is now 1

If 1 <= 0:  # False
    Stop
    
Add 1 to x  # x was 5 and adding 1 to x yields x = 6
n = 1 - 1   # n is now 0

If 0 <= 0:  # True
    Stop    # stop the program

What is x?

5   If-else and loop constructs

The “if-else” and loop constructs are very important in any programming. Again, the above logic is not Python code. It’s pseudocode. Forget about Python syntax for now. That will be useless if you don’t understand these constructs.

6   Functions

A function is a group of statements that are used to achieve a common goal. It can take arguments as inputs and return something as outputs. Some functions do not take any inputs or do not return anything. Some programming languages have a different name, subroutines, for functions that do not return anything.

Let’s say you want to take two points and calculate the distance between them.

Function CalculateDistance(point1, point2):
    Find x and y coordinates of point1 and call them x1 and y1, respectively
    Find x and y coordinates of point2 and call them x2 and y2, respectively
    Using Pythagoras' theorem, calculate the distance between the two points
    Return the distance

This task is not a simple single-line statement, so if you need to repeat it many times, it will make more sense to create a function for this calculation. See also the Pythagorean theorem or Pythagoras’ theorem.

In any programming, it will almost always be good to reduce redundancy or repetitiveness. Let me define a much simpler function that just adds two numbers and 1.

Function SpecialAdd(x, y):
    Return x + y + 1

Your special add adds two numbers x and y, and additionally adds 1. Now, you can use this function like this:

SpecialAdd(1, 2)  # 1 + 2 + 1 is 4
SpecialAdd(2, 3)  # 2 + 3 + 1 is 6

7   Variables

You have this code that calculates the area of a rectangle 10 by 4:

Area is 10 * 4

Put this line in a function:

Function CalculateArea():
    Return 10 * 4

You can call this function like CalculateArea(), but can you use it for any other rectangles in different dimensions? No because this function can only calculate the area of a 10-by-4 rectangle. It is not very useful. Let’s improve it:

Function CalculateArea(width, height):
    area = width * height
    Return area

Is it more useful now? Let’s try:

area1 = CalculateArea(10, 4)  # 40
area2 = CalculateArea(2, 5)   # 10

We call width, height, area, area1, and area2 variables because they can vary depending on assigned values. We call 10 and 4 in the original function CalculateArea() literals because they are literally 10 and 4, and cannot change.

8   Sets and arrays

What is a set? A group of elements.

Set A = {1, 2, 3} and set B = {2, 3, 1} are the same because *sets* are unordered. If they have the same elements in them in any order, they are identical.

What is an array? An array is a set of ordered elements.

Array C = [1, 2, 3] and array D = [2, 3, 1] are different because they have different orders.

9   Indexing

How do we access individual elements in an array? By indexing. Some programming languages use 1-based indexing and some others 0-based indexing. Python uses 0-based indexing. What does it mean? Let’s take an example of the array C above. How would you access 1 verbally? I would say, take the 1st element from array C. What about 3? Take the 3rd element from array C. This is 1-based indexing. Let’s try 0-based indexing. We just start from 0 instead of 1. To access 1, take the 0th element from array C. What about 3? Take the 2nd element from array C.

Let me give you more examples about indexing. I’ll use 1-based indexing for now.

You have an array A = [1, 4, 9, 16, 25, 36, 49]. Have you noticed the pattern? Yes, it’s the squares of 1 through 7, but that’s irrelevant here. I want to print all the elements except the first two and last two elements. That is, 9, 16, and 25 only. How would you solve this problem? Of course, you can just write your pseudocode like this:

For each x in 9, 16, and 25:
    Print x

OK... I didn’t expect that answer because what if your A changes? You need to use indexing.

A = [1, 4, 9, 16, 25, 36, 49]
For each element x in A:
    Print x

What does the above code do? Yes, it prints every element. Let’s try 1-based indexing to solve my original question.

A = [1, 4, 9, 16, 25, 36, 49]
For each index i in 3, 4, and 5:
    Take the i'th element from A and print it

A little better, right? At least, it answers my question, but this is not good code because it cannot handle different sizes of A. Let’s add two more elements to A without changing any other code.

A = [1, 4, 9, 16, 25, 36, 49, 64, 81]
For each index i in 3, 4, and 5:
    Take the i'th element from A and print it

Does it work? No because now it skips the last four elements instead of two. We need to improve our algorithm like this:

A = [1, 4, 9, 16, 25, 36, 49, 64, 81]
For each index i in 3 up to the size of A minus 2:
    Take the i'th element from A and print it

In this specific case, the size of A is 9 and that minus 2 is 7. Now, it prints 9, 16, 25, 36, and 49. This code can take any arrays that have five or more elements. Why five or more elements? Can you explain why? Think about it.

10   Homework: Why do we use loops in programming?

Can you guess why we use loops over unrolled statements? Please submit your report in FirstLastname_WhyLoops.pdf to D2L. There will be penalties for filename and format violations (-2 points for each).

11   Homework: Print an array

You have an array (an ordered set of items) with 19, 122, 32, 34, and 62. Please write your pseudocode that prints out each item per line in that order using a loop construct. Submit your pseudocode in FirstLastname_PrintArray.txt to D2L. There will be penalties for filename and format violations (-2 points for each).

12   Homework: Reverse an array

You have an array (an ordered set of items) with 121, 129, 213, 42, and 15. You can access individual items directly using their place numbers 1, 2, 3, 4, and 5. How would you reverse the order of these items and put them in a new array such that the new array has 15, 42, 213, 129, and 121? Use a loop construct. Submit your pseudocode in FirstLastname_ReverseArray.txt to D2L. There will be penalties for filename and format violations (-2 points for each).

13   Homework: Add two arrays element-wise

You have two arrays A = [21, 32, 31, 34, 56] and B = [119, 122, 323, 414, 155]. They are of the same size. That is important because you will have to add one element from A and another from B, both from the same index. For example, 21+119, 32+122, 31+323, 34+414, and 56+155. Print each addition per line. Use a loop construct. Please implement this addition algorithm using 1-based indexing. Submit your pseudocode in FirstLastname_ElementwiseAddition.txt to D2L. There will be penalties for filename and format violations (-2 points for each).