Python, the Basics (Part 2)

Jon Reades

Conditions

Conditions & Consequences

The simplest condition only considers one outcome:

if <condition is true>:
    #...do something...

But you’ll often needs something a little more sophisticated:

if <condition is true>:
    #...do something...
elif <some other condition is true>:
    #...do something else...
else:
    #...if no conditions are true...

#...code continues...

For Example

if x < y:
  print("x is less than y")
else:
  print("x is not less than y"

Or:

if x < y:
  print("x is less than y")
elif x > y:
  print("x is greater than y")
else:
  print("x equals y")

Conditional Syntax

The most common sources of syntax errors in conditions are:

  1. Incorrect indenting;
  2. Missing colons on conditional code;
  3. Unbalanced parentheses;
  4. Incorrect logic.

All of Them Together (Input)!

if hours >= 0:
print("Hours were worked.")
else
    print "No hours were worked.")

All four errors can be found here, can you spot them?

All of Them Together (Output)!

Output from the Python interpreter:

>>> if hours >= 0:
... print("Hours were worked.")
  File "<stdin>", line 2
    print("Hours were worked.")
    ^
IndentationError: expected an indented block
>>> else
  File "<stdin>", line 1
    else
    ^
SyntaxError: invalid syntax
>>>     print "No hours were worked.")
  File "<stdin>", line 1
    print "No hours were worked.")
    ^
IndentationError: unexpected indent

That’s Better!

It’s relatively straightforward to figure out the syntax errors, but the logical error is much less obvious. Over time, you become far more likely to make logical errors than syntactical ones.

if hours > 0:
    print("Hours were worked.")
else:
    print("No hours were worked.")

Comment Your Code

Make Your Life Easy (Well, Easier)

Always comment your code:

  1. So that you know what is going on.
  2. So that you know why it is going on.
  3. So that others can read your code.
  4. To help you plan your code

Different Comment Styles

# This is a short comment
print("Foo")
print("Bar") # Also a short comment

# ------- New Section --------
# You can have comments span multiple
# lines just by adding more '#' at the 
# start of the line.

# You can keep code from running
# print("Baz")

Comments Follow Indentation

# Function for processing occupational data
# from the 2001 and 2011 Censuses.
def occ_data(df):
  #  Columns of interest
  cols = ['Managerial','Professional','Technical']
    
  # Integrate results into single dataset -- 
  # right now we don't replicate Jordan's approach of
  # grouping them into 'knowledge worker' and 'other'. 
  for i in df.iterrows():
    # For each column...
    for j in cols:
      # Do something
      ...

Easier Multi-Line Comments

The below are not real comments, but they can help when you have a really long comment that you want to make. They are also used to help explain what a function does (called a docstring).

"""
So I was thinking that what we need here is 
a way to handle the case where the data is
incomplete or contains an observation that we
weren't expecting (e.g. "N/A" instead of "0").
"""

Tips

Some useful tips for commenting your code:

  • Include general information at the top of your programming file.
  • Assume the person reading the code is a coder themselves.
  • Good commenting is sparse in the sense that it is used judiciously, and concise without being gnomic.
  • Use comments to track the logic of your code (especially in conditionals and loops)

More Resources

Here are some links to videos on LinkedIn Learning that might help, and YouTube will undoubtedly have lots more options and styles of learning: