Tuesday, May 21, 2024

Lab 2: Python Fundamentals

This weeks lab assignment was very simple and straight forward since it focused on Python fundamentals. The lab consisted on manipulating strings and lists using indexing and loops. 

values = [0, 1, 2, 3, 4, 5, 6, 7]
print(values[2:5])
sl = slice(2, 5)
print(values[sl])
# Expected Output: [2, 3, 4]
Figure 1: Sequence Slicing

The first part of the lab was assigning a variable of string literals stored in a list. With the first string being our first name and the second or last index our surname. Once the list was declared and initialized we were expected to print our surname. 

Negative subscripts is not uncommon for programing languages but Python's syntax is rather convenient and powerful.  If you dig under the hood some you may notice that it is a short notation for a slice object. So the code shown in Figure 1 shows two ways to achive the same outcome.

Typically, one would use the shorthand notation but in situation where you must use a slice multiple times it is nice to reuse the same slice object.

The next part of the lab required us to split a string literal, our name, using a blank space delimiter to create a list of string literals and print the last index.

Continuing to the next section of the assignment, which was to correct some typos or syntax errors found in a for-loop. Again this was rather straight forward and easy to complete.

Steps 3, involved creating a while loop which appended 20 random numbers between 0 and 10 to a list. I provided the while loop but found this expression to be unnecessaryly verbose and error prone verses using a list comprehension expression. Which brings me to a point provided in my summary of PEP 20 - The Zen of Python, the idea that, "There should be one-- and preferably only one --obvious way to do it." is just outright silly! If you are interested in expanding your Python and leveraging the simple, beauty of list comprehension see §5.1.3 of the Python documentation.

Section 4 of the lab's code was practice for typical if-else expressions and finally the list method remove. All in all the lab was a breeze with the final output shown in Figure Two below.

Figure 2: Output from Mod2_ML.py Script

The lab instruction also requested a flow chart of the final python script. Considering the script contains multiple operations grouped into 4 sections but is sequentially executed (top-down) makes for a rather interesting flow-chart. Idealy the distince operation would be represented as independent function or classes which whould have their own flowchart and be referenced within the final sequence of python code. Nonetheless, in the flowchart created, the for-loops sequence is placed in its own flowchart, see Figure Three.

Figure 3: Flowchart of final script

No comments: