L03 - Variables and Data Types
L03 - Variables and Data Types
Semester 1, 2021
Lecture 3,
Variables and Data Types
COMMONWEALTH OF AUSTRALIA
WARNING
2
Week 2: Variables, Data Types
We will cover: Variables, Data types (bool, int, float and string),
You should read: Sections 1.2 of Sedgewick
Lecture 3: Variables and Data Types
Binarynumbers
TRUE = 1, FALSE = 0
[1]Why have I written “Boolean” here and not boolean? Because a Boolean variable is
named after George Boole, who developed the concept of what we now call Boolean algebra
in 1854. The variable type in Java uses the lower-case ‘b’ because it’s a primitive type, and
the naming convention for primitives is to use a lower case. 5
Integers are stored asbinary
All integers can be thought of as binary numbers: 0, 1, 10, 11, 100, 101, ...:
2 10 1× 21 + 0× 20
3 11 21 + 20
5 101 22 + 20
6
Bytes
00000000 =0
00000001 =1
In fact everything in your computer
00000010 =2
is stored as bits.
00000100 =4
00001000 =8 A byte is eight bits.
00010000 = 16
00100000 = 32 Bit means “binary digit”.
01000000 = 64
10000000 = 128
76543210 b i t s
7
Bits
1s and 0s are easy to store as “on” and “off” so binary has become
the universal way to store all electronic information.
which is equal to
E.g.,
01101010 = 0 + 64 + 32 + 0 + 8 + 0 + 2 + 0 = 106
8
Hexadecimal
10
Variables
11
Variables (cont.)
Here any time we need to get the value of x we just call it by name.
The name doesn’t matter: it’s just a label.
12
Declare → Initialise → Use
int total;
total = 0;
total = total + 5;
13
Declare → Initialise → Use
String message;
message = "Hello!";
System.out.println(message);
You have to have things in this order, else there will be ...trouble.
14
Declare → Initialise → Use
int total;
total = 0
total = total + 5
So you have to declare/initialise a variable before you use it: you have to
decide what type you need first, like an integer, character or string,
before you start using it.
Code that misses the declaration out or gets it in the wrong order, like
this:
1 print(" the temperature is " + temperature )
16is / 33
INFO1110 2020 S2 Dr. John Stavrakak
2 temperature = 26
Simply won’tcompile:
> python DeclareVariables.py
Traceback (most recent call last):
File "DeclareVariables.py", line 1, in <module>
print("the temperature is " + temperature)
NameError: name ’temperature’ is not defined
Initialising variables
17
Initialising variables(cont.)
18
Scope: variables have a lifetime
In the code you’ve seen so far the variables have been short-lived and
this hasn’t mattered one bit.
In the programs we are writing now, without classes or functions, the
variables introduced will live until the end of the program.
1
2
x=5
if True:
3
print( x)
4
y=7
5
if True:
6
print( x)
7 print( y)
8 z=3
9 print ( x)
10 print ( y)
11 print ( z)
This is a very important concept for you to remember because they have
to be tracked. Later in the course we will revisit the idea of scope.
Data types of variables
Primitive types are the simplest type of variables e.g. an integer (int). They
use a fixed amount of memory. Simple math operations e.g. + - * / % can
use the value stored in that variable, or store the result...but in Python,
everything is an Object!
Objects are blocks of memory that contain related data and associated
operations for that data. An integer is represented within an object as a
sequence of bits and we can perform operations such as addition,
subtraction etc.
One object can contain many other Objects. The amount of memory used
by an Object can change over time. They can have customised operators
defined by the programmer.
Data types of variables
Python provides builtin types to hold information for numbers and text.
Python 2
21
Data types of variables (cont.)
Python 3 (thiscourse)
Name Kind Memory Range
bool boolean 1 byte True or Fales
int integer unknow No limit
float Floating-point may be 8 bytes depends on
platform
str string Value [0, verylong]
dependent
22
Boolean variables
You will come across Boolean variables very commonly, and you will
mainly use them to test whether certain things are true or not.
Boolean variables
Expression Evaluates to
True and True True
True and False False
False and True False
False and False False
Expression Evaluates to
True or True True
True or False True
False or True True
False or False False
Expression Evaluates to
not True False
not False True
Expression Evaluates to
not True False
not False True
(1 == 2) or (2 == 2) = ?
Mixing Boolean and Comparison Operators
(1 == 2) or (2 == 2) = ?
True
Boolean code example
1 foo = True
2 bar = False
3 flag = foo
4 flag = foo and bar
5 print(" flag = " + str( flag ))
The above shows how you can initialise and operate on a Boolean
variable called flag.
Notes:
You use the values true and false directly;
You can assign the value of one boolean variable to another;
You can calculate the result of two boolean values with &
operator.
30
Int example
1 a = 45
2 b = 23
3 c =a + b
4 p r i n t ( s t r ( a ) +" +" +s t r ( b) +" =" +s t r ( c) )
Note how I had to separate the parts of the equation that I wanted to
print out. If I had put just this:
• The range and the accuracy of floating point types depends on how
many bits are used in the coefficient, and the exponent. Python will
manage this automatically.
32
Float example
1 radius = 0 .51238761523
2 area = radius * radius * 3 .141592659
3 print(" The area of a circle of radius “ + str( radius) + " is " + str( area) )
33
Float example (cont.)
Note that I used the multiplication sign ‘*’, rather than something like
“ˆ2”, which doesn’t mean squared. There is a symbol for power, it is **
e.g. x ** 2.
First identify the information that is going to be stored and how that
changes over time.
accuracy if you are only dealing with integer values, integers are
exact but floating point numbers are not
35
When to use integer or floating point
36
A character
37
The string type
A string datatype is a sequence of characters stringed together to
represent text information.
a string is an object
it can have a few characters or several thousand.
it has special operators to query or manipulate the text
information.
1 msg = " HELLO "
String msg
memory
char 0 char 1 char 2 char 3 char 4
address
H E L L O
38
The string operators (str)
39
String example
1
word1 = " Hello "
2
word2 = " World !"
3
twoWords = word1 + word2
4
print( twoWords)
5
6
word1len = len( word1 )
7
print(" string word1 has " + str( word1len ) + " characters.")
8
print(" string two Words has " + str( len ( twoWords)) + " characters.")
9
1
0 isequal = ( word1 == word2 )
1 print(" Does string word1 match string word2 ? "+ str( isequal) )
1
• string looks more complicated than int and float. There is internal
data and many operators.
• The methods are called and used to query the string object for
information.
41