The simplest condition only considers one outcome:
But you’ll often needs something a little more sophisticated:
Or:
The most common sources of syntax errors in conditions are:
All four errors can be found here, can you spot them?
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
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.
Always comment your code:
# 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
...
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
).
Some useful tips for commenting your code:
Here are some links to videos on LinkedIn Learning that might help, and YouTube will undoubtedly have lots more options and styles of learning:
Python, the Basics • Jon Reades
Comment Your Code