Lecture 1c
This lecture covers assignments in Python, introduces tools for writing and running Python code, and familiarises students with the coursework submission process.
Variable and Assignment in Python
Variable assignment in Python uses the = operator. This binds the variable name to an object.
When a variable is reassigned, it is bound to a new object, and the old object is not changed.
Updating a variable involves changing its value based on its old value. For example, x = x + 1 retrieves the current value of x, evaluates x + 1, and then binds x to the new value.
Python offers shorthand operators for updating variables
+= (addition)
-= (subtraction)
*= (multiplication)
Tools for Writing and Running Python Code
Anaconda is a Python distribution that bundles many data science tools, including:
Python
Spyder IDE
Popular data science Python modules (NumPy, Pandas)
conda (Anaconda's package manager)
Jupyter Notebook
Spyder is an Integrated Development Environment (IDE) used in this course.
Editor: for writing code.
Shell: for interacting with and running code.
Other functionalities: debugger, variable explorer, etc.
Other Python IDEs like PyCharm and Visual Studio Code can be used, but AI features should be disabled.
Running Python Code in Spyder
Interactive execution: Type code in the shell and press Enter.
Run file: Execute all code in a file using the "Run file" button (or F5).
Run selection/current line: Execute selected code using the "Run selection or current line" button (or F9).
Working with .py Files
Python code is typically stored in .py files and run directly.
Only objects printed using print() are visible in the console.
Spyder Features
Code completion: Use the Tab key for suggestions, speeding up code writing and reducing errors.
Help: Get function information in the "Help" tab or by pressing Ctrl+I (Command+I on Mac).
Variable explorer: Browse variables in the "Variable explorer" tab.
History: View previously run code in the "History" tab.
Printing with f-strings
Formatted String Literals (f-strings) allow embedding Python expressions within strings.
Prefix the string with f or F.
Enclose expressions in curly braces: {expression}.