Part 1 – Part 2 – Part 3 –Part 4 – Part 5 – Part 6 – Part 7
I plan to get my Microsoft Technology Associate certificate in Python programming and figured I’d take my notes publicly as I prepare. Call it learning in public or review notes or whatever – I’m just interested in passing on my first attempt.
My aim is to review the topics I already know and cover topics I might have missed. I will link resources as opportunities arise. There will be lots of code examples provided, if for no other reason than to prove to myself that things work the way I expect.
I’m certainly interested in corrections if I have something blatantly wrong. However, the point of these posts isn’t to go super deep on each topic or act as a tutorial, but rather to act as a broad overview review of the topics (with perhaps some deeper dives where necessary) for this exam. I think it’s safe to say that if you don’t understand the code examples I provide here, you should review the corresponding topic in the Python documentation and other deep-dive tutorials.
Here’s the first of six categories in Microsoft’s description of the test:
Evaluate an expression to identify the data type Python will assign to each variable
This seems pretty simple.
>>> type("string") <class 'str'> >>> type(1) <class 'int'> >>> type(1.1) <class 'float'> >>> type(True) <class 'bool'>
I’m guessing that Microsoft is not in fact going to be asking me about the type()
method, but is probably more likely to throw a list of values at me and ask me to predict what data type Python would assign to each in a variable. Python 3.7 has a number of other built-in data types, but they’ve specified just str, int, float, and bool, which are pretty straightforward.
Another useful method here is isinstance
. It takes two arguments: an object and a data type, then returns True or False based on whether the object is of the indicated data type.
>>> isinstance("string", str) True >>> isinstance("string", int) False >>> isinstance(1.1, int) False >>> isinstance(1, int) True >>> isinstance(False, bool) True
Perform data and data type operations
Convert from one data type to another
Again, this is a pretty straightforward topic:
# Convert an int to a string >>> one = 1 >>> type(one) <class 'int'> >>> one = str(one) >>> type(one) <class 'str'> # and back >>> one = int(one) >>> type(one) <class 'int'> # Convert a string to a float >>> point = "1.1" >>> type(point) <class 'str'> >>> point = float(point) >>> type(point) <class 'float'>
Here’s what the error looks like when we try to convert something that isn’t correct:
>>> int("one") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'one'
The most nuance will come in converting expressions to boolean (True/False) statements. The Python documentation on Truth Value Testing lists the following built-in objects that will evaluate to false:
- constants defined to be false:
None
andFalse
. - zero of any numeric type:
0
,0.0
,0j
,Decimal(0)
,Fraction(0, 1)
- empty sequences and collections:
''
,()
,[]
,{}
,set()
,range(0)
This means that our earlier variables should evaluate as true:
>>> bool(one) True >>> bool(point) True
Let’s check to make sure a number of items evaluate as false as expected:
>>> bool(0.0) False >>> bool({}) False >>> bool([]) False >>> bool("") False >>> bool(0) False >>> bool(None) False
Everything seems to check out so far.
Construct data structures
This is where study and review come in handy, because I wasn’t immediately certain what precise structures this description was referencing. Even the Python documentation on Data Structures doesn’t explicitly define the term, but this helpful blog post states: “There are four built-in data structures in Python – list, tuple, dictionary, and set.” Now we’re talking.
I’m going to assume this is asking for the most basic level of simply defining data structures and that we’ll cover methods associated with each of these later.
Lists
Lists hold an ordered collection of variables. Typically it is best to include the same data type for all objects in a list:
>>> instrument_list = ["Moog One", "Jupiter 8", "Synthstrom Deluge", "TR-808"] >>> number_list = [1, 13, 42, 77, 101]
But it’s also possible to mix data types:
random_list = ["squirrel", 1.1, True, -5]
The list()
function itself (read more here) takes any iterable (like a string or tuple) and turns it into a list:
>>> hello_world = list("hello world") >>> hello_world ['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
Tuples
Off the top of my head, I’d describe tuples as exactly like lists except that they are immutable. My understanding is that it is best practice to use a tuple instead of a list if it is not going to be changed over the course of a program. They are defined in the same way as lists except by using parentheses instead of square brackets:
>>> tupelo = ("honey", "barbeque", "florida") >>> tupelo ('honey', 'barbeque', 'florida')
One thing to note is that since strings can be defined with parentheses, it’s important to add a trailing comma in a one-item tuple. Note that failing to do this will result in a str
data type being assigned:
# no comma >>> question = ("is this a tuple?") >>> type(question) <class 'str'> # with a comma >>> question = ("is this a tuple?",) >>> type(question) <class 'tuple'>
Dictionaries
Dictionaries are unordered collections of key-value pairs. A single-line definition of a single-item dictionary might look like this:
me = {"name" : "Danny"}
But dictionaries typically have more items:
disney_villains = { "Aladdin" : "Jafar", "Hercules" : "Hades", "The Little Mermaid" : "Ursula", "The Lion King" : "Scar" }
The dict()
function (docs) will create a dictionary from any number of key-value pairs using this syntax:
>>> state_capitals = dict(Cali="Sacramento", NewYork="Albany", Florida="Tally") >>> state_capitals {'Cali': 'Sacramento', 'NewYork': 'Albany', 'Florida': 'Tally'}
Sets
I know that sets are collections of unique items and that there is a set()
function one can use to turn a list into a set, but I haven’t used these much in my programs to date. Further research shows that sets are unordered, which I’m not sure I knew before. Here’s an article teaching the topic.
So this is new to me! Sets can be defined simply by putting single variables in a comma-separated list within curly brackets:
>>> a = {1, 2, 3} >>> type(a) <class 'set'>
This is not true for empty sets:
>>> b = {} >>> type(b) <class 'dict'>
To instantiate an empty set, one simply calls the set()
function:
>>> c = set() >>> type(c) <class 'set'> >>> c set()
Perform index and slicing operations
So we have our data structures. How can we access, set, and otherwise manipulate the data within them? Note that, being unordered and not having key values, sets generally don’t support indexing or slicing.
Indexing
Being ordered, members of lists and tuples can be accessed with their zero-indexed indices using this syntax:
# list >>> instrument_list = ["Moog One", "Jupiter 8", "Synthstrom Deluge", "TR-808"] >>> instrument_list[0] 'Moog One'
Using a negative index will count from the end of the list, meaning that -1 will return the last item in a list or tuple:
# tuple >>> instrument_list = ("Moog One", "Jupiter 8", "Synthstrom Deluge", "TR-808") >>> instrument_list[-1] 'TR-808'
We can use indices to assign values within lists as well. (This does not work with tuples because they are immutable.)
>>> instrument_list = ["Moog One", "Jupiter 8", "Synthstrom Deluge", "TR-808"] >>> instrument_list[1] = "Volca FM" # much more affordable >>> instrument_list ['Moog One', 'Volca FM', 'Synthstrom Deluge', 'TR-808']
Dictionaries are similar, but we use keys within square brackets to access the associated values:
>>> disney_villains = { "Aladdin" : "Jafar", "Hercules" : "Hades", "The Little Mermaid" : "Ursula", "The Lion King" : "Scar" } >>> disney_villains["Aladdin"] 'Jafar'
New items can be added to dictionaries by referencing a new key and assigning a value all at once:
>>> disney_villains["The Jungle Book"] = "Shere Khan" >>> disney_villains {'Aladdin': 'Jafar', 'Hercules': 'Hades', 'The Little Mermaid': 'Ursula', 'The Lion King': 'Scar', 'The Jungle Book': 'Shere Khan'}
We can delete items from lists or dictionaries by referencing their index or key with the del
keyword:
>>> instrument_list = ['Moog One', 'Volca FM', 'Synthstrom Deluge', 'TR-808'] >>> del instrument_list[0] # also a little more than I can afford right now >>> instrument_list ['Volca FM', 'Synthstrom Deluge', 'TR-808'] >>> del disney_villains['The Jungle Book'] >>> disney_villains {'Aladdin': 'Jafar', 'Hercules': 'Hades', 'The Little Mermaid': 'Ursula', 'The Lion King': 'Scar'}
Slicing
In a basic sense, slicing allows us to select a subset of a list or tuple using the following syntax:
list_or_tuple[start:stop_but_not_inclusive:step]
Stop is required and is not inclusive (so setting to 5 will include only through subscript 4). Start and step are optional. If we skip start, it starts at 0 by default (syntax: [:4]
). So if we wanted to select the middle items of our instrument list, we’d use:
>>> instrument_list = ['Moog One', 'Volca FM', 'Synthstrom Deluge', 'TR-808'] >>> instrument_list[1:3] ['Volca FM', 'Synthstrom Deluge']
Or perhaps the second and fourth items:
>>> instrument_list[1:4:2] ['Volca FM', 'TR-808']
We can also mix and match positive and negative values:
>>> instrument_list[0:-2] ['Moog One', 'Volca FM']
Here’s a good article on indexing and slicing in Python that has some nice slicing tricks worth reviewing.
Determine the sequence of execution based on operator precedence
Is this just asking about the classic mathematical order of operations? Mathematically, the order of operations is parentheses, exponents, multiplication, division, addition, and subtraction (“please excuse my dear aunt sally”). Python basically follows what we’d expect on these basics. However, there’s a number of other operators to throw into the mix, as this article describes:
Operators Usage { } Parentheses (grouping) f(args…) Function call x[index:index] Slicing x[index] Subscription x.attribute Attribute reference ** Exponent ~x Bitwise not +x, -x Positive, negative *, /, % Product, division, remainder +, – Addition, subtraction <<, >> Shifts left/right & Bitwise AND ^ Bitwise XOR | Bitwise OR in, not in, is, is not, <, <=, >, >=, <>, !=, == Comparisons, membership, identity not x Boolean NOT and Boolean AND or Boolean OR lambda Lambda expression
Of this list, Microsoft specifies the following operators:
Assignment
Easy:
variable_name = variable_value
See above for assignment within data structures.
Comparison
The above list from the linked article shows these comparison operators:
<, <=, >, >=, <>, !=, ==
Comparison operators are pretty basic math and don’t require much review, except that I didn’t recognize <> as being used in the Python language. Doing a little searching, I found a StackOverflow answer that links to the documentation showing that the <> (not equal) operator has been removed from Python 3, so I’d guess Microsoft is unlikely to use this.
Logical
These include the and
, or
, and not
operators. Some quick examples with boolean values:
>>> True and True True >>> True and False False >>> True or False True >>> not True False >>> not False True >>> not True and False False >>> not False and True True
Arithmetic
In addition to the expected mathematical operators of +, -, *, and /, Python also has:
1) Modulus, which provides the remainder after a division:
>>> 11 % 3 2 >>> 2 % 2 0
2) Exponent, where you perform a calculation of one number to the power of a second number:
>>> 3**2 9 >>> 10**3 1000
3) Floor division (I know it better as integer division), where the decimal in the result is truncated:
>>> 7//3 2
Compare this to normal division:
>>> 7/3 2.3333333333333335
Identity
The is
and is not
operators are probably the most nuanced ones here. The is
operator returns true if the two items being compared both point to the same object or false otherwise, whereas the is not
operator returns false if the two items point to the same object or true otherwise.
>>> 1 is 1 True >>> 1 is 1.1 False >>> one = 1 >>> 1 is one True >>> 1 is not 1.1 True >>> 2 is not 1 True >>> "one" is not "one" False >>> "one" is "one" True >>> one = "one" >>> one is "one" True
Python is an object-oriented language, and basically everything we deal with in the language is an object. Python is also pretty damn smart, so rather than create two identical objects, it tends to point to the same object when two things are alike. We can check this out using the id()
function, which returns the memory address of the specified object:
>>> eleven = "11" >>> id(eleven) 16397216 >>> id("11") 16397216
Containment/Membership
The in
and not in
operators check a specified sequence (such as a list or string) and checks for a given value within that sequence, then returns True or False as per logic.
>>> 1 not in [2, 3, 4, 5] True >>> 1 not in [1, 2, 3] False >>> 2 in [3, 4, 5] False >>> 2 in [2, 2, 2, 3] True >>> "ring" in "string" True >>> "wring" in "string" False
Select the appropriate operator to achieve the intended result
Finally, this is where practice and experience come in – and where paying for the practice test might come in handy. That said, I feel extremely confident about this first section, so depending how the rest goes, I might indeed be able to avoid that expense.
I’ll aim for a post on each of the categories Microsoft has listed. Next up: control flow with decisions and loops.