Variables and data types#

What you will learn in lesson:

  • What is a variable

  • Naming rules for variables

  • Types of variables

  • Data conversion

What is a variable?#

A variable in Python is a symbolic name that references a chunk of memory where information is stored and can be accessed or modified later. We can have as many variables as we want, as long as they have unique names.

x = 4
x
4
y = 100 + 25
y
125
# In an interactive environment, we can type variable to get value
x
4
# Or we can use the print() function we learned earlier to view assigned value
print(x)
4
# We can also reassign variable
x = 5
x
5
# We can perform operations between variables
x + y
130
# An even save the outputs from operations into a new variable
z = x + y
z
130
# We can also delete a variable with function del()
del(x)

x
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
Cell In[8], line 4
      1 # We can also delete a variable with function del()
      2 del(x)
----> 4 x

NameError: name 'x' is not defined

Like we mentioned earlier, a variable references a chunk of memory. How can we know this memory? By using the function id(). This memory is unique to every variable created in Python.

The ID is for the variable, not the variable’s value: In layman’s terms, two variables with the same value will have different memory locations ( Exception: if the number is between -5 and 256 or a simple string with no spaces, it will not be given a unique ID for memory optimization purposes).

x = 1
print(id(x))
print(hex(x)) # hex() just allows you to output this in hexadecimal representation
8909800
0x1
a = 278
b = 278
# Both variables have the same value...
print(a)
print(b) 
278
278
# But different memory addresses
print(id(a)) 
print(id(b))
139919121182192
139919121178064

Variable naming#

These is the list of allowed characters in a variable name:

  • Lowercase and uppercase letters: a-z and A-Z

  • Numbers: 0-9

  • Underscores: _

In addition, there are the following two rules:

  1. Variable names must start with a letter or the underscore character and can not start with a number.

x = 1
_foo = 35
3foo= 12
  Cell In[14], line 1
    3foo= 12
    ^
SyntaxError: invalid decimal literal
  1. Names are case-sensitive.

myvar=10
myVar=20

print(hex(id(myvar)))
print(hex(id(myVar)))
0x87f508
0x87f648

Note

You can name your variables any way you like as long as you follow the aforementioned rules. But, the convention in Python is to follow the snake case, in contrast to camel case.

When naming a variable using multiple words, the camel case prefer to join them together, without any white space and delineating the start of each new word with a capital letter. For example, in camel case we would write “thisVar”.

In contrast, snake case uses an underscore (“_”) between these words and use always lower case: “this_var”.

Note

Camel-case convetion is used for class names though. We will see this in the future.

Reserved names (keywords)#

There are certain names that can not be used for variables. These are reserved keywords that have specific meanings and restrictions on how they should be used.

Some examples (We will be covering most of them throughout the course):

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

Variable types#

So far we have only used numbers as values assigned to a variable. However, Python has more data types.

  • Floating-point number: A positive or negative number with decimal points.

float_var = 3.1416
  • Boolean. A variables with only two values: true (1) or false (0).

bool_var = True
  • string: array of characters (We will see this data type in more detail in a future lesson).

string_var = 'virginia' 

Python has a built-in function called type(), which can be used to determine the data type that a variable is holding:

type(float_var)
float
type(bool_var)
bool
type(string_var)
str

Python has another built-in function, isinstance() , which can check if a given variable is of specific type. The ouput to this function will be a boolean, that is, True if the specified object is of the specified type, otherwise False.

# example giving a True
isinstance(float_var, float)
True
# example giving a False
isinstance(float_var, str)
False

You can also pass a several types to check. In this case, the second argument in this function, instead of a single type, is a collection of types all contained within parenthesis and separated by commas, i.e., (type1, type2, type3...).

# You can also pass several options to check

isinstance("Hello", (float, int, str))
True

Note

This collection of objects within parenthesis is called a tuple. This is a typical data structrue in Python, aiming to store data in particular way. We will get to this when we study data structures.

Converting Data Types#

When needed we can ‘cast’ a variable as a different data type (remember Python automatically assigns data type to a variable).

We do this through casting functions:

int()

# create float variable
var_float = 9.6
type(var_float)
float
# cast float to integer
var_int = int(var_float)

print(type(var_int))
var_int
<class 'int'>
9

float()

# create string variable
var_str = '10.2'
type(var_str)
str
# cast string to float
var_float = float(var_str)
print(type(var_float))
print(var_float)
<class 'float'>
10.2

Practice exercises#

Exercise 3

Define two variables “a” and “b” both taking the same value between -5 and 256. Show that both variables have the same memory address. Repeat the same operation, but with a value outside the aforementioned range. Do variables still have the same memory address?

# Your answers here

Exercise 4

1 - Assign the integer 100 to a variable called “num1”.
2 - Assign the number 25.67 to a variable called “num2”.
3 - Assign the boolean value False to a variable called “flag”.
4 - Use the print function to print each variable along with its data type using the type() function.

# Your answers here

Exercise 5

1 - Create a variable “integer_var” and assign it the value 10.
2 - Create another variable “float_var” and assign it the value 3.5.
3 - Create a variable called “result” that stores the sum of “integer_var” and “float_var”.
4 - Print the value of “result” and its data type.

# Your answers here