The concepts here build upon chapter 2 and the videos in Lesson 3. A complimentary page of examples is Prof Cravens page on using Python as a calculator.
A variable can be thought of as a "box" that holds an "object". In the image below, you can see that there is a box with a number "inside" it. This object is of type (or class) float, and it has been given the name pressure.
In code, we would say:
pressure = 3.14159
This one line of code would create a variable using the assignment operator where:
name = pressure
type = float (or <class 'float'>)
value = 3.14159
There are many types of object in Python. Those considered the most basic are:
string (str) or text
integer (int) meaning any full number
float (float) is a number with a decimal point
boolean (bool) can have only one of two values, either True or False
There are other types of object as well - that are a little more complex - we will look at also such as:
A list that holds a sequence of objects, e.g. [2, 3.6, True, "Hello"] which we can mutate
A tuple that holds a sequence of objects, e.g. (2, 3.6, True, "Hello") which we cannot mutate (immutable)
A dict which holds a key-value pair, e.g. my_dict = {1: "Peter", 2: "Mary"} where keys must be unique and values can be any class (type). More on this later.
There are also many others, but these are the ones we'll use. Later we can create our own types- this is called Object Oriented Programming- we will be able to create objects such as "Human", or "Player" or "Alien" or "Meteor".
summary of python data types
We will use almost (but not quite) all of the data types shown here, over the duration of this course.
A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume).
Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
While these are the rules, some guidelines are:
use descriptive names- a verb-noun can be useful such as quantity_selected, user_choice etc.
use snake_case for variables and functions, compliant with the PEP-8 style guide
always lowercase, avoid numbers, NEVER use non-alphanumeric characters! Variable names are case-sensitive.
Avoid using Python keywords (e.g., if, else, for) as variable names.
Avoid using builtin functions as variable names
#Legal variable names:
myvar = "John"
my_var = "John"
_my_var = "John"
myVar = "John"
MYVAR = "John"
myvar2 = "John"
#Illegal variable names:
2myvar = "John"
my-var = "John"
my var = "John"
Just because it is legal does not mean we should do it- it is legal to drink 30 pints of Guinness ! Note that variables names are case sensitive, so my_var is completely different from my_Var.
In some languages we might declare a variable before we give it a value, or declare and initialise (give it a value) at the same time. In Java, for example, here we create two variables. Once we declare them, we can never change the type to anything else, i.e. both of the ints created will forever be integers- they cannot become strings, or floats, or booleans.
// Java program to create two variables and print them
public class Main {
public static void main(String[] args) {
// Good
int minutesPerHour;
minutesPerHour = 77;
// OK, but not so easy to understand what m actually is
int m = 60;
System.out.println(minutesPerHour);
System.out.println(m);
}
}
In python, it is dynamically typed, so we usually create and initialise at the same time.
Usually assigning values to variables in python is done like this:
x = 10
x = "Now a string"
To do the same program above in python, we can assign two values at one time!
# Python program to create two variables and print them
minutes_per_hour, m = 77, 60
print(minutes_per_hour)
print(m)
Python allows assigning the same value to multiple variables in a single line, which can be useful for initializing variables with the same value.
a = b = c = 100
print(a, b, c)
will result in:
100 100 100
We can also change the data-type of these variables into any other "thing" in python, such as a str, bool, float etc.
Unlike Java and many other languages, Python variables do not require explicit declaration of type.
The type of the variable is inferred based on the value assigned.
In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. You can run the code in the visualizer to see how Python handles objects with the same value and how the equality (==) differs from the identity (check id with the is operator).
A constant does not change, so "under the hood", things such as numbers and strings do not actually change. To clarify:
a constant never changes- like math.pi or the value for pi (3.14159...) does not change
In Python, any variable may be changed. In some other languages you can declare a variable as a constant and it can never then be changed, either by Thor's hammer or Odin's beard. If there is a variable that you wish to remain with the same value for the duration of your program, the convention is to capitalise that variable, e.g. SCREEN_WIDTH = 640 communicates to the reader that the variable SCREEN_WIDTH is not be be changed - should not be changed. It does not mean that it cannot be changed- this is important.
variables may point to different values, but once these values are created, they will not change.
user = "Mary"
user_age = 22
user = "Tom"
user_age = 31
while the values stored in or pointed to by user and user_age have certainly changed, all we have done is pointed those references to new boxes holding the values of Tom and 31. The actual boxes that held "Mary" and 22 are unchanged, and now just lost in memory. There is a bit of code called a garbage collector that looks for and picks up "lost objects" and removes them. This may make more sense later, but the point is that the values have not changed, we've essentially ignored them and created new ones.
All of the operators below are implemented "under the hood" (or at a level that we cannot readily see) in the code as functions that are referred to as methods. A method "works" on a class. 3.1 + 7 is permitted because both of these objects- while being technically different as an int and a float- belong to the same parent class of "num", which is an abstract class. This abstract class is not explicit- we cannot create a "num", but we can certainly create and use the children or sub-classes of num, which are float, int and bool.
The most frequently used and best known operators. Keep in mind that operators are implemented differently "under the hood" and may- or may not work across different types/classes. Under the hood, the familiar operators are known referred to as add, sub, mul, div and so on- not hard to guess which one is called what.
We will look in more depth at these later, but keep in mind what objects you can compare:
an int with an int
an int with a float
an int with a bool
a str with a str
a str with an int?
a str with a list?
"Under the hood" the relational operators are "known" by references such as gt, lt, eq, ne, gte, lte and so on- can you guess what these abbreviations may stand for?
These correspond with the logical gates, and are common also to database queries and expressions in spreadsheets. Though the nsyntax will vary by application and language, these are fundamental concepts of computer science.
Yes, there is more than the humble = available, mostly to be used as a succinct (but arguably less readable) form of assignment.
Note than one can also use
*= so if x were 7, running x *= 3 would result in x having a value of 21
/= so if x were 7, running x /= 3 would result in x having a value of 2.3333333333333335
//= so if x were 7, running x //= 3 would result in x having a value of 2
-= so if x were 7, running x -= 3 would result in x having a value of 4
This will apply the same logic: more difficult - initially at least - to follow, but often used as shorthand.
Bitwise operators operate on operands at a binary level. Meaning the bitwise operator looks directly at the binary digits or binary bits of an integer. Hence the name bitwise (bit by bit operation). The only one of these that we will look at it the inversion, or bitwise NOT method.
There are two types of special operators in the python programming language.
As the name suggests the identity operators compare the id (identity) of two or more python objects such as variables, values, and many more. In other words, others say that the identity operator can also be used to compare the memory locations of two objects.
Membership operators are used to verifying whether a particular element is a part of a sequence or not. Now a sequence can be a list, string, sets, dictionary, and tuples.