Variables in Python 3

Before understanding variables in python, we need to understand why they are used. Actually, the main task of a computer program is data processing. This data can be very diverse (at first glance), but in the computer’s memory, it is always ultimately converted into a specific sequence of binary numbers.

To access data, a computer program (regardless of the programming language used) utilizes large numbers of variables of different types.

Definition of Variable

A variable is a name that refers to a value.

Actually, a variable in a programming language acts as a reference pointing to a memory address. This means it refers to a specific location in Random Access Memory (RAM) where a certain value (the data) is stored as a sequence of binary numbers. However, this does not necessarily mean that the value is a single number in the perspective of the programming language used.

This can be done through any “object” stored in the computer’s memory. For example, it could be:

  • An integer number
  • A floating-point number
  • A text string
  • A list
  • A formatted sequence
  • A table or function, etc.

Variable Names:

Variable names are names that you can freely assign (almost), but try to choose them carefully. It is preferable that they are short, clear, and meaningful, so they accurately represent what the variable contains. These meaningful are called mnemonic variable names (memory-friendly names).

For example, variable names like “height” or “altitude” are more appropriate and descriptive than simply using “x” or something meaningless like “x1q3z9ahd”. Such Good programming practice ensures that the lines of code in a program are easy to read.

Rules for Naming Variables in Python:

In Python, variable names must follow some basic rules:

  • A variable name consists of a sequence of letters (A to Z, a to z) and numbers (0 to 9), but it must always start with a letter.
  • Only letters, numbers, and underscores (_) are allowed.
  • Spaces and special characters (such as !@#$%^&*()[]{} etc.) are not permitted, except for the underscore _.
  • Case sensitivity is important:
    • Joseph, joseph, and JOSEPH are three different variables in Python.
    • It is recommended to use lowercase letters for most variable names, following a common convention.
    • CamelCase (e.g., TableOfContents) can be used for better readability.

Reserved Keywords (Cannot Be Used as Variable Names)

In addition to the above rules, Python has 33 reserved words that cannot be used as variable names because they are part of the language itself:

and      as      assert   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  

Some examples of invalid names:

76trombones = 'big parade'   # starts with number
more@ = 1000000             # invalid symbol
class = 'something'         # keyword

Assigning a Value to a Variable

Now that we know how to choose a variable name wisely, let’s explain how to assign a value to a variable.

The term “assigning a value” refers to the process of linking a variable name with a value (its content).

In Python, as in many other programming languages, this process is done using the equals sign (=):

n = 7  # Assigning the value 7 to the variable n
msg = "How are you?"  # Assigning the value "How are you?" to the variable msg
pi = 3.14159  # Assigning the value 3.14159 to the variable pi

Displaying or printing the value of a Variable:

Consider, we now have three variables: n, msg, and pi. To display the value of a variable on the screen, you can use print() function:

msg = "How are you?"
print(msg) 

You can print variables using print () function. In earlier versions of Python, the role of the print() function was performed by the print statement (making it a reserved keyword). This statement was used without parentheses, so you had to write print n or print msg. But in Python 3, you must add parentheses after each print statement to convert it into a function (some tools can do this automatically).

print(n)
print (msg)
print(pi)

The type of a variable depends on the value it holds. You can use type function to print the type of a variable.

type(message)  # str
type(n)        # int
type(pi)       # float

Multiple Assignments

In Python, you can assign the same value to multiple variables at once, for example:

x = y = 7  
print(x)
print(y)

You can also assign different values to multiple variables simultaneously:

a, b, c  = 4, 8.33, 10
print(a)
print(b)
print(c)

In this example, a and b receive different values at the same time:
  • a = 4
  • b = 8.33

Reassigning a value to a variable:

We know, that it is possible to reassign a new value to a variable—either once or multiple times as needed. When we reassign a value, we replace the old value with a new one for the same variable.

altitude = 320
print(altitude)
altitude = 375
print(altitude)

Note: We must not confuse the assignment operator (=) in Python with the equality symbol (=) used in mathematics. Many people misinterpret the statement altitude = 320 as if it denotes equality, which is not the case!

  • Firstly, equality is a commutative operation in mathematics, whereas assignment is not. For example, writing a = 7 or 7 = a is the same in mathematics, but in programming, writing altitude = 375 in reverse would not make sense.
  • Secondly, equality is always true in mathematics, whereas in Python, a variable’s value can change using the assignment operator (=), as we have seen before.

For example, in mathematics, we assert that A = B at the beginning of a proof and assume that this equality remains valid throughout all subsequent calculations. In programming, however, the first assignment simply sets a value, and later statements may change it.

For example, suppose we have two variables, a and c, containing the values 3 and 5, respectively, and we want to swap their values.

a = 5
b = a  # 'b' now holds the same value as 'a'
b = 2  # 'b' now holds a different value from 'a'

Exercise

After performing the operation manually, you will likely find a way to do it more efficiently. Most programming languages provide shortcuts for such tasks (like swapping variables). Python offers an elegant and specialized syntax for swapping values:

a, b = b, a

Note: You can, of course, swap more than two variables, such as three or more, using the same statement.

Important Note: Assignment Rules

In an assignment statement:

  • The variable name must be on the left of the = sign.
  • The expression must be on the right.

This differs from mathematics, where = denotes equality. In Python, = is an assignment operator. For example, m + 1 = b is invalid. However, constructs like a = a + 1 (incrementing a by 1) are common in programming, even though they’re mathematically nonsensical. 

In this article, we will learn will about Operators in Python.

No Comments

Leave a Reply