0% found this document useful (0 votes)
10 views

L03 - Variables and Data Types

Uploaded by

Kevin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

L03 - Variables and Data Types

Uploaded by

Kevin
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Introduction to Programming

Semester 1, 2021
Lecture 3,
Variables and Data Types

Slides based on material by John Stavrakakis and that provided for


Sections 1.2 ofSedgewick . All rights reserved
Copyright Warning

COMMONWEALTH OF AUSTRALIA

Copyright Regulations 1969

WARNING

This material has been reproduced and communicated to you by or


on behalf of the University of Sydney pursuant to Part VB of the
Copyright Act 1968 (the Act).

The material in this communication may be subject to copyright


under the Act. Any further reproduction or communication of this
material by you may be the subject of copyright protection under
the Act.

Do not remove this notice.

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

It helps to know about binary numbers in your programming,


because everything in a computer is stored in binary digits (bits).

You can think of Boolean[1] values as binary numbers (in a


sense)

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, ...:

Base 10 Base 2 / binary expansion


0 0 0
1 1 1 × 20

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.

If the bits are


d7d6d5d4d3d2d1d0

then the total value is

d727 + d626 + d525 + d424 + d323 + d222 + d121 + d020

which is equal to

128d7 + 64d6 + 32d5 + 16d4 + 8d3 + 4d2 + 2d1 + d0

E.g.,
01101010 = 0 + 64 + 32 + 0 + 8 + 0 + 2 + 0 = 106
8
Hexadecimal

Sometimes it’s handy to have a more binary hexadecimal decimal

compact way to store numbers in a 0000 0 0


0001 1 1
range that’s a power of two.
0010 2 2
Noting that 24 is 16, we use the first
0011 3 3
6 letters of the alphabet to represent
0100 4 4
10, 11, . . . , 15.
0101 5 5
0110 6 6
This is more compact: a byte just
0111 7 7
takes 2 characters: 00 (0) to FF (255). 1000 8 8
1001 9 9
To indicate that a number is to be
1010 A 10
interpreted in this way we put 0x in
1011 B 11
front: 0x00 and 0xFF.
1100 C 12
Two-byte numbers need four such
1101 D 13
characters, so look like this: 0x0000 1110 E 14
to 0xFFFF (65535). 1111 F 15
9
Variables

10
Variables

Programs would be pretty simple and useless if they couldn’t handle


data that could take different values. What if we wanted to print
something other than “Hello World!” or “I’m sorry Dave, I can’t let you
do that” ?

1 print(" You bought 4 items")


2 print(" It costs you $12 .50 ")
3 print(" Served by autobot 526 on 24 /02 /2021 ")

To do this we need to have some variables.

11
Variables (cont.)

A variable is a piece of information that’s stored in memory so we


can access it by giving its name later, like this:
1 x = 4
2 y = 8
3 z =x + y

 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

Declare Initialise Use

int total;

total = 0;
total = total + 5;

13
Declare → Initialise → Use

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

Python declare and initialise in one step.

Declare Initialise Use

int total;

total = 0

total = total + 5

It is strongly encouraged that you initialise every variable. Life will be


easier.
15
Variables must be declared before they’re used

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

Variables have to be initialised.


Initialising is giving the very first value to a variable.

Good programmers always initialise their variables to something


useful.

In Python, almost all variables are initialised when they are


introduced.
1 num = get_ user_ guess ()
2 # we have to declare msg , so I just use any value
3 msg = 'ponyrides in the wilderness'
4 if num == 34:
5
msg = 'correct‘
print( msg )
6

17
Initialising variables(cont.)

1 num = get_ user_ guess ()


2 msg = ' incorrect '
3 if num == 34:
4 msg = ' correct ‘
5 print( msg )

1 num = get_ user_ guess ()


2 if num == 34:
3 msg = 'correct’
4 else:
5 msg = 'incorrect’
6 print( msg )

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

Name Kind Memory Range


bool boolean 1 byte True or False
int integer 4 bytes [−2147483638,2147483647]
float Floating-point 8bytes ≈ ±2.23× 10−308 to ±1.80× 10308

str string Value [0, verylong]


dependent

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

A Boolean variable, in Python, is assigned a value True or False.

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

The and Operator’s Truth Table

Expression Evaluates to
True and True True
True and False False
False and True False
False and False False

Examples: True and True => result = True


True and False => result = False
Boolean variables

The or Operator’s Truth Table

Expression Evaluates to
True or True True
True or False True
False or True True
False or False False

Examples: False orTrue => result = True


False or False => result = False
Boolean variables

The not Operator’s Truth Table

Expression Evaluates to
not True False
not False True

Examples: not True


not not not not not not True
Boolean variables

The not Operator’s Truth Table

Expression Evaluates to
not True False
not False True

Examples: not True => result = False


not not not not not not True => result = True
Mixing Boolean and Comparison Operators

(4 < 5) and (5 < 6) = ?

(4 < 5) and (9 < 6 ) =?

(1 == 2) or (2 == 2) = ?
Mixing Boolean and Comparison Operators

(4 < 5) and (5 < 6) = ?


True

(4 < 5) and (9 < 6 ) =?


False

(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) )

Compiling and running the above we get


~> python IntTest.py
45 + 23 = 68

Note how I had to separate the parts of the equation that I wanted to
print out. If I had put just this:

1 p r i n t ( s t r ( a +b) +" =" +s t r ( c) )

then I would have seen the output


68 = 68

...which isn’t as interesting.


31
Float variables

• To represent numbers using a decimal point e.g. 3.14, 0.0023,


−6.21 × 103

• float is referred to as floating point types.

• Typical float type uses 4 bytes of memory, but Python 3+ has


arbitrary precision.

• 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) )

Compiling and running the above we get this:

~> python FloatTest.py


The area of a circle of radius 0.51238761523 is 0.8247970926722155

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.

To square a number, it’s simplest to multiply it by itself explicitly. To

To raise a number to a power, use this:


1 radius = 0.4
2 volume = pow ( r a d i u s , 3 . 0 ) * 4 . 0 / 3 . 0 * 3 . 1 4 1 5 9 2 6
You can also get a more accurate from Python itself than
trying to remember π:
1 import math
2 radius = 0.4
3 volume = pow ( radius , 3.0) * 4.0 / 3.4 * math . pi
4 print(" The volume of the sphere is " + volume)
When to use integer or floating point

First identify the information that is going to be stored and how that
changes over time.

Are they whole numbers or can there be a fractional component?

accuracy if you are only dealing with integer values, integers are
exact but floating point numbers are not

range If you’re dealing with very large or very small numbers,


you have to use floating point types: their range is much
bigger.

35
When to use integer or floating point

In this course, you should pick either int or float.

Is there any danger of using a floating point type in your


program if only integers are expected?

36
A character

• A character is an human defined symbol. The letter ’A’, the


letter π, a punctuation mark ;
• Each character is in fact a graphic. It is stored in the computer.

• Displaying the character requires identification among many


characters. A number is used.

• A character set is a mapping from a numbers to characters.

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)

+ operator. Creates a new string from the concatenation of two


existing strings.

len() method - returns an integer. The number of characters in the


string.

== operator - returns a boolean value. True if this string matches


another,
False otherwise.
many many more!

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

The above, when compiled and run, gives


HelloWorld!
The string word1 has 5 characters.
The string twoWords has 11 characters.
Does string word1 match text of word2 ? false
Stringnotes

• 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.

• string is a good example of a reference type, which is a very important


part of object-oriented programming that we will learn a great deal
more about. Because strings are so useful, we will begin using them
now.

• None then it means it has no memory associated with it — and you


really shouldn’t use it or very bad things will happen!

41

You might also like