CMPT 120: Topic: Python's Building Blocks - Variables, Values, and Types
CMPT 120: Topic: Python's Building Blocks - Variables, Values, and Types
2
In this lecture we shall cover
• Python’s building blocks
• Variables
• Values
• Types
• and Literal values
3
Learning outcomes
At the end of this course, a student is expected to:
• Describe and apply fundamental concepts and
terminology of Python:
• Literals, variables, types,
4
From what we already know
to new knowledge
• As we learn to develop software this term
• we shall acquire new knowledge and skills
AND
• we shall also make use of knowledge we
have already learnt
5
In the real world, there are …
Real World
• Objects e.g.:
and
• Actions e.g.:
6
In the computer world, there
are …
Real World Computer World
• Objects • Data
• Variables (objects)
• Literal values
Expressions
• Actions • Statements
• Operators
• Functions + methods
7
Variable
• We saw in Lecture 3 that computers are very
good at manipulating lot’s of data
8
Variable
• Definition: A variable is a
• memory location
• to which we give a name
• to which we assign a value of a particular
data type
memory
snack
“Apple”
12
Variable – Demo - 2
• Let’s demonstrate
• How to use a variable
• In doing so, we shall introduce the
output built-in function ”print” (output statement)
13
Variable – Demo - 3
• Let’s demonstrate
• How to assign another value to an already
existing variable
• In doing so, we shall use the
Assignment operator “=“ (assignment statement)
• Example: in C
float pi; <- variable declaration
pi = 3.14; <- variable initialized
// area of circle = pi r2
areaCircle = pi * pow(radius,2)<- variable used
16
GPS (Good Programming
Style) - 1
• Variable name must be descriptive, i.e., it must
describe the purpose of the variable or the
meaning of its value
• For example:
• Why?
• Creates self-documented code
17
It follows that …
• Reusing variable for different purposes is never a
good idea!
• For example:
• Why?
18
GPS (Good Programming
Style) - 2
• We cannot use a Python keyword as a variable
name
• Python keywords: Section 2.3 (page 11) of our
online textbook
• For example:
• Why?
19
Skill: Hand-tracing Python code
• Let’s “hand-trace” the following Python code:
apple = 0.75
juice = 1.65
sandwich = 4.80
lunch = apple + juice + sandwich
and in doing so, let’s see how we can represent
a variable (and its value) in memory:
20
Lastly: literal value
• Examples
The values in red are literal values:
apple = 0.75
juice = 1.65
sandwich = 4.80
21