BAA1118 - Foundations of Programming for Analytics & AI
print() at least onceNameError and survivedEverything in this module is built on one idea:
Data is stored in objects. Objects have a type. The type decides what you are allowed to do.
A DataFrame in week 7 is just a very large object with a very particular type. Today is the foundation for all of it.
revenue is the name1500 is the value= is the assignment operatorRead it right to left: “take 1500, and label it revenue”.
= is not the mathematical equals. Equality is ==, which we will see later today.
Once assigned, the name can be used anywhere the value could be used.
A name can be reused. The old value is simply forgotten.
counter = counter + 1 looks like nonsense in maths and is completely normal in code. The right-hand side is computed first, then stored under the same name.
Python requires:
2024_sales is invalid, sales_2024 is fineSales, sales and SALES are three namesThese 35 words belong to Python. Using one as a name is an error:
False None True and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield
The dangerous ones in analytics are sum, list, type, max, min, id and str. They are not reserved, but they are existing function names, and overwriting them breaks things quietly.
Python convention (not enforced, but universal):
snake_case for variables and functions: total_revenue, mean_pricedf is fine for a working DataFrame, x1 is not fine for revenuesales_2024, compute_margin()Try storing a value with the following names. Which of these are valid?
The function type() tells you what you are holding.
| Type | Name | Example | Used for |
|---|---|---|---|
int |
integer | 42 |
counts, years, ids |
float |
decimal | 4.2 |
prices, measurements |
str |
string | "forty two" |
text, labels, categories |
bool |
boolean | True |
yes/no, filters |
NoneType |
nothing | None |
missing, not set yet |
Next week adds list, dict, tuple and set. Week 7 adds Series and DataFrame.
Same operator +, three different behaviours. Read the type before blaming the operator.
9
5
14
3.5
Python follows normal mathematical precedence: ** first, then * / // %, then + -.
Tip
Use brackets even when they are unnecessary. (revenue - costs) / revenue costs nothing and removes all doubt.
19
19.46
19.5
An invoice has a net amount of €1,847.35. Irish standard VAT is 23%.
net + vat == gross return True? Why might it not?Single or double quotes, as long as they match:
Use the other kind of quote when your text contains one:
This is the single most common error when reading data from a file: the column looks numeric, and is stored as text. We will meet it again in week 7.
Concatenating with + becomes painful fast. f-strings are the modern solution:
Selling 340 units at 12.99 euros gives 4416.6 euros
f before the quote turns on the feature{} is Python code, evaluated and insertedRevenue: 4416.60
Revenue: 4,416.60
Revenue: 4416.60|
Share: 25.3%
This is how every number in a report should be printed.
A method is a function attached to an object, called with a dot.
ireland
Ireland
IRELAND
Éire
['revenue', 'costs', 'profit']
True
True
20
Data cleaning in week 7 is mostly these five methods applied to a whole column at once.
Python counts from zero.
P
y
n
Pyt
Important
Zero-indexing and “up to but not including” apply everywhere in Python: strings, lists, DataFrames. Learn it once, this week.
Somebody typed their university into a web form. This is what came back:
Tidy it up, in four steps:
raw holds the messy valueclean: no spaces at the start or end, and each word starting with a capital. Two methods, one after the other.raw, then how many are in cleanThe last line answers: is "City" inside clean?
| Operator | Meaning |
|---|---|
== |
equal to |
!= |
not equal to |
< > |
less than, greater than |
<= >= |
less or equal, greater or equal |
in |
is contained in |
Warning
= assigns, == compares. Writing if x = 5 is a SyntaxError, and it happens to everyone.
False
True
True
String comparison is alphabetical, and case matters. Lowercase everything before comparing text from real data.
True
True
True
and: both must be trueor: at least one must be truenot: flips the answerPython uses the English words, not && and ||. Week 7 will use & and | for columns, which is a different thing.
42
3.14
42
False True False
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) Cell In[40], line 1 ----> 1 int("forty two") ValueError: invalid literal for int() with base 10: 'forty two'
The second one is a classic: int() will not go via float. Use int(float("42.5")).
input() asks the user for a value, and always returns a string.
We will not use input() much: notebooks and data files replace it. But knowing it returns text explains a lot of beginner bugs.
A survey exported these three values, all as text:
R_0042 (34) spends 3.79 per year of ageTrue if the respondent spent more than 100 and is under 40
Thanks for your attention and don’t hesitate to ask if you have any questions!