Subscribe Contact

Home  »  Chapter 2 : Programming Basics
Variables

Overview

Variables in Python are labels (names) that we assign to represent datum elements. As programmers, we choose what we want to use as variable names, within some constraints based on rules (see the list below). Variable naming is often based on naming standards within a course or company where you're working. Generally speaking, variable naming is based on clear connections between the datum value and the concept it represents. Continuing the example of age, the ideal variable name to store an age is age. We could use any variable name for that value, however using something like x to store age, while valid, is less understandable for those reading or maintaining our code.

Note: The discussion on this page includes a few highlights from the Style Guide for Python Code which contains more extensive coverage of coding conventions for Python code.

Variable Name Rules in Python

  • Variable names are case-sensitive. The variables age, Age, AGe, AGE are 4 separate variables.
  • Variables must start with an alphabetic character or an underscore.
  • Variables cannot start with a number.
  • Variables can only contain alphabetic characters, digits 0 thru 9, and the underscore character.

Variable Value Assignment

Once we have a datum and have decided on a variable name to use to attach to it, we assign the datum value to the variable using the assignment operator, which in Python is the equal sign. The variable appears first, then the assignment operator, and then the value, as shown here ...



Variables & Memory

When we assign a value to a variable, the value is stored in the computer's memory (RAM). The location in memory is assigned a memory address by the operating system. Our variable is the label for the memory location, which is much easier for us to read and remember than a raw memory address value such as 0x1b1271b6c30. Here is a diagram that depicts this scenario. We have declared the age variable in our Python program and assigned the value 25 to it. In memory, 25 is stored in a memory cell and our age variable is used as the label for that memory location.



Python is a Dynamically Typed Language

It is important to be aware that Python is dynamically typed. What does this mean? In some programming languages to assign a value to a variable, we must first declare the data type of that variable. That is called static typing, which is also often called safe typing. With this safety in place, if I declare a variable as an int then I cannot assign a value of another data type to that variable.

In Python, on the other hand, we do not declare the data type of our variables. Python dynamically recognizes the data type based on the value we are assigning to the variable. So in our example above, writing age = 25 is interpreted by Python to mean that the variable age is of type integer. This is convenient, but it can be potentially problematic if later in the program we write age = "Young". In a strict-typed language, this would produce an error. This is not an error in Python, age would now contain "Young" as its value and its data type would now be a string. If we did not mean to change the data type of age, we could run into a problem with this reassignment. Here's what this would look like in PyCharm:




Let's take a look at an example of variable assignments for our data entry screen example from the previous page about Data & Data Types. The image below depicts our data entry form filled in by Bob Smith. Also, in my Python code file (Demo.py) I've written out variables to show how that data could be set to variables:


Note the following about the Python code in the Demo.py file shown above:

Multiple Variable Assignments

Python supports assigning the same value to more than one variable, like this:

x = y = z = 0
print(x)
print(y)
print(z)
person1, person2, person3 = "Bob", "Sally", "Joe"
print(person1)
print(person2)
print(person3)
The output of the above example would look like this:


0
0
0
Bob
Sally
Joe


Based on the example above, answer the following question...

Question 1

Explain why the output shown above looks the way it does.


Checking a Variable's Data Type

Since Python is dynamically typed, there are times when we may not be sure what data type a particular variable is at any given point in a program. Python has a function called type() that we can use to check the type of a variable. Here is an example of Python's dynamic typing and using the type() function:

x = 10
print(type(x))
x = "Bob"
print(type(x))
x = 3.14
print(type(x))

The output of the above example would look like this:


class 'int'
class 'str'
class 'float'



Note that we dynamically changed the data type of the variable x three times, and each print statement of type(x) demonstrated that x changes each time we assign a value.

Based on the example above, answer the following question...

Question 2

What is the output of the following code?

a = 3000
b = 10.6
a = "Three Thousand"
a = True
a = b
print(type(a))


Variable Case

As indicated previously, Python is case-sensitive. When we are creating variables for data values we have some choices on how we decide to apply the case to those variables. For example, we have used age as a variable several times now, which is a simple and clear variable name. What if we wanted to create a variable like aggregatemonthlysales? It is a descriptive variable name but can be hard to read. There are a few ways to help the readability of variables like this multi-word variable. Each of these approaches has names:

Name Example Description
Camel Case aggregateMonthlySales Camel case is structured so that the first word of a multi-word variable name is lower-case, then the first letter of each subsequent word in the name is upper-case. Other examples: firstName, maxBudget, hitPoints.
Pascal Case AggregateMonthlySales Pascal case is structured with every word in a multi-word name has its first letter upper-case. Other examples: FirstName, MaxBudget, HitPoints.
Snake Case aggregate_monthly_sales Snake case is structured with each word lower-case and separated by underscores. Other examples: first_name, max_budget, hit_points. According to the Style Guide for Python Code, Snake Case is the standard for variable names in Python.

Python Reserved Words

The Python language has a set of reserved words which are used strictly by the language. When we create variables, we cannot use any of these reserved words. The following table provides a list of these reserved words (current as of Python 3.9):

and as assert async await break
class continue def del elif else
except False finally for from global
if import in is lambda None
nonlocal not or pass raise return
True try while with yield __peg_parser__

Practice Problem

Problem 1

Write a Python program that creates variables and assigns values that fulfill the following description. You will need to interpret the English description into the appropriate datum and data types, and then create variables with descriptive names:

Scenario: In a game system users create a game character with specific attributes. The user is prompted for information about themselves and asks them to choose player attributes from lists of choices. The user information the system asks for includes their first name, age, city, state, and country. The game player attributes include player name, player type (such as Warrior, Wizard, Elf, etc.), player age, player gender, and primary weapon. Based on the user's choices, we will also need variables for hit points (a decimal number), strength (a whole number), and experience points (a whole number) and we will also track if they are actively playing the game (yes or no).

Note: For this problem, we are only focused on creating variables and making data assignments to those variables (you can create the values as you wish). We are not trying to code anything further, yet. We will build upon this as we progress in the book.



 

«  Previous : Data & Data Types
Next : User Input  »




© 2023 John Gordon
Cascade Street Publishing, LLC