2.1 Python's Core Data Types
The following table gives a preview of the variety of data types that are built-into Python. They are the building blocks of all the code that will be written in this course. The data types at the beginning of the list are the most basic and they become more complex as you proceed down.
**Data Types used throughout this course
Objects, when created, correspond to a certain memory region to which a unique memory address is associated and in which we store:
data
information about the date
functions that act upon the data
Data-Type - Concept Check
2.2 Numbers/Math
Refer to the Numeric Operators link here and in the left column of this web page.
Multiplication is not recognized implicitly like in Algebra. Therefore you must be explicit when using multiplication:
>>> 2(3)
TypeError: 'int' object is not callable
You must be explicit:
>>> 2*3
6
Division is also unique. The output of division is always a float:
int/int = float()
>>> 3/2
1.5
>>> 2/3
0.6666666666666666
>>> 4/2
2.0
There may be an occasion where the decimal part of a quotient is not needed. In this case any decimal component of the real outcome is removed - truncated - by using the division character twice (//).
>>> 3//2
1
>>> 2//3
0
>>> 4//2
2
Note: the outputs below are all returned as integers, not floats as with regular division. If a float is required, one of the numbers will need to be a float
>>> 3//2.0
1.0
>>> 2.0//3
0.0
>>> 4.0//2.0
2.0
The modulus operator (%) returns the remainder after division is complete.
>>> 3%2
1
>>> 2/3 #is the output a surprise?
2
>>> 15/6
3
In Python precedence determines in what order operators will be executed.
Python evaluates arithmetic expression according to precedence:
>>> 2**3+2*2 #power has higher precedence so is executed first
12 #followed by multiplication, then addition
Precedence can be overruled using parenthesis:
>>> 2**(3+2*2)
128
Operators of equal precedence will be executed in order from left to right.
>>>5/3*2 #integer division 5/3 = 1.6666666666666667
3.3333333333333335
>>>5//3*2 #integer division 5//3 = 1
2
Numbers/Math - Practice
Numbers/Math - Concept Check
2.3 Variables
Variables, in Python, are references to objects in the computers memory.
For example:
>>> x = 123
creates the object 123, somewhere in memory and gives it the tag x. We can
also say that x is a reference to the object or even that it "points" to the object.
>>> id(x) #asking for the memory location of x
4301289696
>>> id(123) #asking for the memory location of 123
4301289696 #same location
Variable assignment
We use the assignment operator (=) to assign values to a variable. Any data type can be assigned to any valid variable.
>>> a = 5
>>> b = 3.2
>>> c = 'Hello'
There are three assignment statements. 5 is an integer assigned to the variable a. 3.2 is a float that assigned to b. And 'Hello' is a string assigned to c.
Multiple assignments
Multiple assignments can be made in a single statement as follows:
>>> a, b, c = 5, 3.2, 'Hello'
If we want to assign the same value to multiple variables at once:
>>> x = y = z = "same"
This assigns the "same" string to all three variables.
After objects are created they will be referred to by name. For example, the
instruction:
>>> print (x)
prints to the screen the value of the object whose name is x.
One name can not be used by more than one object.
>>> x = 20
>>> x = 43
>>> print (x)
43
The last assignment statement prevails and the object 20 no longer has a name.
Python will automatically delete unnamed objects (garbage collection).
*Names cannot begin with a number and cannot contain a character with
operational meaning (like *, +, -, %).
*for instance: this-name is illegal because it uses the subtraction char,
while this_name is legal
*Common naming conventions are:
A. CamelCase - all words begin with uppercase
B. mixedCase - initial word begins with lowercase and all subsequent words
begin with uppercase.
C. lower_case_with_underscores
*Names cannot coincide with Python's reserved words.
*Names cannot coincide with existing function/class names
*As a rule short AND suggestive names are the best option.
For example:
>>> x = 0.46
is a bad choice for lack of clarity, but:
>>> inflation = 0.46 #inflation rate in Norway
is a good choice (along with the short comment after the #), and is better than the
unnecessarily long, although syntactically correct:
>>> norwegian_inflation_rate = 0.46
Variables - Practice
Variables - Concept Check
2.4 Expressions
Expressions create and process objects.
Example:
>>> word1 = 'Hello' #create string object, using single quotes
>>> word2 = "World" #create string object, using double quotes
>>> punctuation = '!' #create string object
>>> together = word1 + word2 + punctuation #create string object
#by concatenation
>>> print (together) #process string object
HelloWorld!
*note: space is a character and was not included in any of the strings created
>>> word1 = 'Hello ' #word1 now refers to this string object
>>> print(together)
Hello World! #a space was included in word1
Strings and Ints can be used together in an expression only with the multiplication operator. This is used for repetition.
>>> number = 3
>>> print(number * word1)
Otherwise numbers are used with numbers and strings with strings to create expressions.
>>> print(number + word1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
However, numerical strings and numbers can have their type changed in order to create expressions of compatible type.
>>> print(str(number), word1) #the comma in a print statement places
3 Hello #a space between the strings
Also:
>>> value = '7' #create string object
>>> print(int(value)/number) #change string to int and divide
2
>>> print(float(value)/number) #change string to float and divide
2.3333333333333335
>>> print(int(value)%number) #change string to int and get remainder
1
Escape character
*The \ (backslash) is known as an escape character as it will escape the characteristic of the character that follows and just take on the visual aspect of it.
Example:
>>> quote = "Kennedy said, "Ask not . . ."" #quotes for quote
>>> print (quote) #cannot match quotes
SyntaxError: invalid syntax #for str object
Solution 1:
>>> quote = "Kennedy said, \"Ask not . . .\"" #use escape char before
>>> print (quote) #the dble quotes
Kennedy said, "Ask not . . ."
Solution 2:
>>> quote = 'Kennedy said, "Ask not . . ."' #use single quotes
>>> print (quote) #for this string object
Kennedy said, "Ask not . . ." a
Other escape characters:
New Line '\n':
>>> print('Roses are red,\nviolets are blue.')
Roses are red,
Violets are blue.
Tab '\t':
>>>print('Name\t\tAge\tGender\nJohn Doe\t35\tMale')
Name Age Gender
John Doe 35 Male
Expressions - Concept Check
2.5 Boolean Data Type
Any object can be tested for truth value, for use in an if or while condition (these will be covered later), or as an operand of the Boolean operations below.
The following are considered false:
-None
-False
-zero of any numeric type (0, 0.0, etc)
-any empty sequence ('', (), [])
-any empty dictionary ({})
All other values are considered true.
>>> bool(0)
False
>>> bool([]) #empty list
False
>>> bool (2)
True
>>> bool('python') #non-empty string
True
Comparisons
This table summarizes the comparison operations:
Boolean operations also include and, or, and not.
- When using and, both sides of the and must be true for the statement to be true
- When using or, only one side needs to be true for the statement to be true
Two more operations, in and not in, are supported only with sequence types
Examples:
>>> a = 2
>>> b = 3
>>> c = 4
>>> a < b
True
>>> a == c and a < b #the left side is False so whole statement is
False
>>> a == c or a < b #right side is True so whole statement is
True
>>> a < b and b <= float(c) #both sides True
True
>>> a < b <= float(c) #same as previous but chained together
True
>>> 'b' in 'bulldogs' #using in to test for an element in a string
True
>>> a != a
False
>>> a == 2 and (b == c or c > a) #both sides in () False
False #right side is False so statement
Boolean - Concept Check