Variables and Operators
Prof Kathryn Kasmarik
Learning Objectives
After today’s lecture, you will be able to:
Define named variables and constants to hold data in a computer program.
Know some different data types.
Assign data into a variable.
Use augmented assignment.
Pass data from one part of a program to another.
Pass data from a human to a program and vice versa.
Differentiate between local variables and instance variables.
Understand the role of garbage collection.
Revision: UML Class Diagrams
Recall:
UML class diagrams illustrate the data and behaviors a program requires to successfully complete its tasks.
Example of a UML diagram structure:
Simple Pendulum
Variables:
_length (an instance variable)
_GRAVITY (a constant)
Methods:
calculate_period() -> returns a float
calculatelength(desiredperiod) -> returns a float
Program Data
Instance Variables
Definition:
Named pieces of data expected to be accessed by the entire class.
Defined within the ‘init’ method.
Naming Convention:
Utilizes the prefix
_to indicate protected access.Example:
self._length
Constants
Definition:
Similar to variables, but their values are not intended to change.
Examples:
self._GRAVITYmath.pi
Naming Conventions
Python programmers utilize the convention of
_names_like_thisto signal that the data in the variable is private.Important Considerations:
Should not be accessed from outside the class it’s declared in.
Use descriptive names for variables:
Helps in remembering the stored data.
Assists others in understanding your code.
Reserved Words:
Certain words cannot be used as variable names, such as:
if,for, which are part of the Python language syntax.
Data Types
Definition:
Data types are implied by the kind of data stored in a variable.
Notably, the data type of a variable can change dynamically.
Example data types include:
Integer (int)
Floating-point number (float)
String (string)
Assignment
The assignment operator (
=) assigns a piece of data to a variable.Methods of data assignment:
Hard coded values.
Transferred from another variable.
Assignment from a Calculation
Basic math operators available in Python include:
Addition:
+Subtraction:
-Division:
/Multiplication:
*Exponentiation:
**(power of)
Other available operators:
Built-in functions, e.g.,
abs(-5).Library function usage, e.g.,
math.sqrt(.).
Order of Operations:
Follows conventional mathematical rules.
Augmented Assignment
Explanation of Long Form vs. Augmented Assignment:
Long form examples:
x = x + 1vs.x += 1y = y - 5vs.y -= 5z = z**2vs.z **= 2p = p / 2vs.p /= 2q = q*5vs.q *= 5
Input from and Output to a Human
Example usage of input and output in Python:
if __name__ == "__main__":
# Input example: asking for pendulum length
length = float(input('How long should the pendulum be in metres?'))
pendulum = SimplePendulum(length) # Create a new pendulum object of given length
current_period = pendulum.calculate_period()
print(f'The current period of the pendulum is {current_period:.2f} seconds.')
desired_period = float(input('How long should the period be in seconds? ')) # usually 1.0s on a clock!
recommended_length = pendulum.calculate_length(desired_period)
print(f'The recommended length for a period of {desired_period:.2f} seconds is {recommended_length:.2f} m')
Local and Instance Variables
Local Variables
Definition:
Named pieces of data used briefly within a function.
Cleaned up by the garbage collector post-usage.
Often used as input and output values in functions.
Instance Variables
Definitions and Examples:
Named pieces of data used persistently within an object.
Garbage Collection
Definition:
A process that unassigns or ‘cleans up’ data that is no longer in use.
Operates as a background process returning unused memory to the available memory pool.
Summary of Learning Outcomes
After today’s lecture, you can:
Define named variables and constants to hold data in a computer program.
Know some different data types.
Assign data into a variable.
Use augmented assignment.
Differentiate between local variables and instance variables.
Understand the role of garbage collection.
Textbook References
Chapter 2 includes:
Variables
Data types: (int, float, string)
Assignment syntax
=Formatted strings
Mathematical operators:
*,**,/Built-in methods:
math.sqrt,print