Computer Science · Ch 5 — Getting Started with Python
Variables
Variables
A variable in a program is uniquely identified by a name — an identifier. In Python, a variable refers to an object: an item or element stored in the memory. The value a variable holds can be a string (for example 'b' or 'Global Citizen'), a numeric value (for example 345), or any combination of alphanumeric characters (such as CD67).
Creating variables with assignment
In Python, an assignment statement both creates a new variable and gives it a value:
gender = 'M'
message = "Keep Smiling"
price = 987.9
The name goes on the left of =, the value on the right. A string value is written inside quotes — double quotes or single quotes both work — while a numeric value is written without any quotes.
The textbook's Program 5-2 displays the values of variables:
#Program: display values of variables
message = "Keep Smiling"
print(message)
userNo = 101
print('User Number is', userNo)
Keep Smiling
User Number is 101
Here message holds a string, so its content sits inside double quotes (single quotes would do equally well), whereas userNo holds the numeric value 101 and therefore takes no quotes at all.
Declaration is implicit
Unlike many languages, Python needs no separate declaration step. Variable declaration is implicit: a variable is automatically declared and defined the first time a value is assigned to it. Two consequences follow:
- A variable must be assigned a value before it is used in an expression. Using a name that has never been assigned raises an error.
- Wherever a variable name appears in an expression, the interpreter replaces it with that variable's current value.
>>> total = count + 5 # count was never assigned
NameError: name 'count' is not defined
Variables in expressions
Program 5-3 computes the area of a rectangle, showing variables being read back inside an expression:
#Program: area of a rectangle
length = 10
breadth = 20 …