Python Programming for AI
What the exam tests
Python questions here are applied: can you choose the right data type, trace a loop or function, and use NumPy and pandas to load, filter, and summarise a dataset without writing a manual loop?
Core concepts
- Core types: int, float, str, bool. Collections: list (ordered, mutable), tuple (ordered, immutable), dict (key–value pairs), set (unique items).
- Control flow: if/elif/else, for over a range or iterable, while with a changing condition, plus break and continue.
- Functions: defined with def, take parameters, return values; default and keyword arguments; local versus global scope.
- NumPy: the ndarray stores same-type values and supports vectorised maths.
a * 2multiplies every element and is far faster than a Python loop. Alsoshape,reshape, broadcasting,mean(),sum(). - pandas: a Series is a labelled 1-D array; a DataFrame is a labelled table. Useful calls:
read_csv(),head(),info(),describe(), boolean filtering,groupby(),fillna(),dropna().
Worked example
import pandas as pd
df = pd.read_csv('marks.csv')
print(df[df['score'] > 40]['score'].mean())
Reasoning: df['score'] > 40 produces a True/False Series; df[...] keeps only rows where it is True; the second ['score'] selects that column; .mean() averages the values, skipping missing ones by default. The output is the average score of students scoring above 40.
Traps that cost marks
- Indentation errors - Python uses indentation, not braces, to define blocks.
- Using
=(assignment) where==(comparison) is needed. - Expecting
7 / 2to give 3; it gives 3.5, while7 // 2gives 3. - Editing a list while looping over it, which silently skips elements.
- Treating a NumPy array like a list:
a + 1adds 1 to every element rather than appending. - Forgetting that pandas column names are case-sensitive.