Python Variables and Data Types

Python Variables and Data Types

posted 10 min read

A. Introduction

Variables are containers of values or data that allow the programmers to manipulate the value indirectly. Variable values can be changed, they can be useful for tracking the state of certain objects. By giving meaningful variable naming, it can improve code readability. In a way variables can make complicated concepts clearer. Imagine we are reading a book on trigonometry, certainly we would see the formula to get the area of a rectangle, the perimeter of a circle, etc.

Data types are the classification of objects such as integer, string, float, boolean, list, dictionary, etc. They are classified to improve the performance of Python, not just Python but for other programming languages. In Python, data is commonly assigned to a variable as part of the language syntax to enhance code abstraction and readability within the program or application.

B. Variables

1. Definition and Creation

Let us say we will store the age of a tree in a variable.

treeage = 5

The treeage is our variable name while the 5 is our data or value. The variable name must be at the left-hand side of the equal sign.

In other languages such as C/c++ we need to define the type.

int treeage = 5;

In Python we don't need it. However you can do so by using typing.

treeage: int = 5

That int is a python standard data type.

2. Naming Conventions

It is very important to know how to name a variable.

a. A variable name must be one word or connected with underscore if more than one


tree age = 5


treeage = 5
tree_age = 5

b. The variable name is case sensitive.

Treeage is different from treeage.

c. The variable name must not start with an integer.


4mycar = 4


my4car = 4
Note: Integers in a variable are allowed but not as the first character.

d. The variable name must not be a keyword

Python has reserved words or keywords that it used internally. They should not be used as a variable name.


for = "mango"

That is not allowed because for is a keyword in Python.

What are the keywords in python?

We can generate Python's keywords using the following code.

import keyword

python_keywords = keyword.kwlist


['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda',
 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Caution: Do not use Python's keyword as a variable name.

3. Variable Scope

There are two basic scopes of a variable they are local and global. Global variables are those whose values can be access anywhere in the code. Local variables are limited to a block where it is defined.

Here is an example of a global and local variables.

num_ships = 10  # global
print(f'initial value of global variable num_ships: {num_ships}')

def get_num_ships():
    # Use the global variable inside the function.
    global num_ships

    local_num_ships = 4  # local
    print(f'local variable num_ships: {local_num_ships}')

    # Access the global variable inside the function.
    print(f'global variable num_ships inside a function: {num_ships}')

    # Modify the value of global variable.    
    num_ships = 20
    print(f'modified global variable num_ships inside a function: {num_ships}')

print(f'global variable num_ships outside the function: {num_ships}')

Run it.



initial value of global variable num_ships: 10
local variable num_ships: 4
global variable num_ships inside a function: 10
modified global variable num_ships inside a function: 20
global variable num_ships outside the function: 20

C. Data Types

Data types are just categories of values such as integer, float or string, etc. This classification is useful to Python to efficiently perform its operations. Each of this data type has its own limit of what operators it can be applied upon. Consider an example, can we divide the name of the planet as str by a number as int? No. Only an integer or float can only be divided by an integer or float. By classifying values Python can easily determine that a string divided by an integer would result to an exception or error.

1. Data Types Overview

Here is an overview of Python's standard data types.

Let me show you how each of them will be used. I will use Python's REPL (Read Eval Print Loop) environment.

To start the REPL you can open your terminal (I will use powershell) and type python.

a. Integer

Integer or int is a whole number that can be negative, zero or positive.

>>> num_employees = 100
>>> isinstance(num_employees, int)
>>> num_brownouts = 0
>>> isinstance(num_brownouts, int)
>>> error_code = -1
>>> isinstance(error_code, int)

b. Float

Floats are decimal numbers with or without fractional parts.

>>> temperature_degree_centigrade = -5.5
>>> isinstance(temperature_degree_centigrade, float)
>>> price = 99.99
>>> isinstance(price, float)
>>> payment = 500.0
>>> isinstance(payment, float)

c. Complex

Complex numbers are numbers that consist of a real and an imaginary part, it is represented as x + yj, where x is the real part, y is the imaginary part, and j is the imaginary unit or the square root of -1.

>>> m = 1 + 3j
>>> isinstance(m, complex)

d. Fraction

Fractions are numbers represented by a whole number numerator and another whole number denominator.

>>> from fractions import Fraction
>>> a = Fraction(223/257)
>>> isinstance(a, Fraction)

e. Decimal

Decimal types are more precise than the float type. This is useful in financial calculations.

>>> from decimal import Decimal
>>> interest_rate = Decimal(0.157)
>>> interest_rate
>>> isinstance(interest_rate, Decimal)

f. Boolean

Boolean takes two values either True or False.

>>> is_running = True
>>> is_sky_diving = False
>>> isinstance(is_running, bool)
>>> is_running
Tip: isinstance is used to check the data type of an object.

g. Set

Set is a collection of unique elements. They are useful for duplicate removals and membership checking.

>>> myset = {45, 60, 5, 3, 1, 15, 5, 45}
>>> # 45 and 5 are duplicates, set automatically removes them
>>> myset
{1, 3, 5, 60, 45, 15}
>>> # check the presence of 3 in the set
>>> 3 in myset
>>> # add 10 in the set
>>> myset.add(10)
>>> myset
{1, 3, 5, 10, 60, 45, 15}
>>> # remove the first value in the set which is 1
>>> myset.pop()
>>> myset
{3, 5, 10, 60, 45, 15}
>>> # remove all values in the set
>>> myset.clear()
>>> myset

h. Dictionary

Dictionary is a data type that belongs to mapping key and value pairs. It is like a lookup table where you supply the key and you will get the value mapped on that key.

>>> user = {'name': 'john', 'age': 32, 'userame': 'jj'}
>>> # get the name
>>> user['name']
>>> # get the age
>>> user['age']

i. List

List is part of the sequence type. It stores objects in sequence.

>>> # list of str or string
>>> fruits = ['mango', 'apple', 'avocado']
>>> fruits
['mango', 'apple', 'avocado']
>>> # get the first fruit in the list
>>> fruits[0]
>>> # get the index of mango
>>> fruits.index('mango')
>>> # list of numbers
>>> numbers = [25, 45, 36]
>>> # list of dictionary
>>> users = [{'name': 'gina', 'username': 'gin'}, {'name': 'peter', 'username': 'pet'}]
>>> # list is mutable meaning you can change its value without changing its memory address
>>> phone_numbers = ['09290651058', '09284056958']
>>> # get the memory address
>>> old_id = id(phone_numbers)
>>> old_id
>>> # add a new phone number
>>> phone_numbers.append('09280232869')
>>> phone_numbers
['09290651058', '09284056958', '09280232869']
>>> new_id = id(phone_numbers)
>>> # if old_id and new_id are the same that means the address is not changed
>>> old_id == new_id
>>> # since the id's are the same, list is mutable

j. Tuple

Tuple is similar to a list except it is immutable. It is defined by enclosing the values in a parenthesis.

>>> mytuple = (25, 9, 78)
>>> # get the value at index 0
>>> mytuple[0]
>>> # to define a single-valued tuple, add a comma
>>> tuple_single = (12,)
>>> # get the type of tuple_single
>>> type(tuple_single)


k. Range

Range is used to store sequences of numbers.

>>> myrange = range(0, 5, 1)

0 is the start argument, 5 is stop argument, and 1 is the step argument.

>>> type(myrange)

>>> # get the value at index 1
>>> myrange[1]
>>> # print the sequence
>>> for n in myrange:
...     print(n)

l. Str

String or str data type stores sequences of characters. String objects are immutable.

Double quotes

region = "South East Asia"

Single quote

car_brand = 'Tesla'

Triple double quotes

country_name = """Philippines"""

Triple single quote

france_capital = '''Paris'''

Since str is a sequence type we can get its index values.

>>> myname = 'Ferdinand'
>>> myname[0]

m. Bytes

Bytes data type is a sequence of byte, they are immutable.

>>> bytes_name = b'peter'

Convert to binary.

>>> binary = []
>>> for byte in bytes_name:
...     binary.append(format(byte, '08b'))
>>> binary
['01110000', '01100101', '01110100', '01100101', '01110010']
>>> # p = '01110000', e = '01100101' and so on.

n. Bytearray

Bytearray is a byte sequence type similar to bytes. But bytearray is mutable and sequence entry can be modified.

message = b'How are you?'

We can change that message to bytearray.

message_ba = bytearray(message)

Let's change the "H" to "N".

>>> message = b'How are you?'
>>> message_ba = bytearray(message)
>>> # convert ascii N to a number as ord("N")
>>> message_ba[0] = ord("N")
>>> message_ba
bytearray(b'Now are you?')
FAQ 1. How to know the data type of a variable or object?
Answer: Use the type(object) class constructor.

2. How to get the memory address of an object?
Answer: Use the id(object) function.

3. What is mutable and immutable objects?
Answer: Mutable objects are those that we can change its value without changing the memory address such as "list", "dict" and others. Immutable objects are the opposite of mutable such as "str", "tuple" and others.

D. Summary

Our world is full of variables and data types. When you are travelling riding a bus at a speed of 40 KPH how long would it take if your destination is 60 KM away? We have an integer of 40 and 60 and assign a variable elapse to calculate the time in hours.

The art of variable naming is essential to easily understand the written code. If your variable is about a number of some oceans, use num_oceans instead of x.

The most common data types that you will encounter are the integer, float, string, and list. Dictionary is one of the most useful types that you can use as you progress. Ultimately you will create your data type through class definitions.

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Python Syntax

Ferdy - Mar 5

Mastering Data Visualization with Matplotlib in Python

Muzzamil Abbas - Apr 18

Git and GitHub for Python Developers A Comprehensive Guide

Tejas Vaij - Apr 7

Mastering Reading and Writing CSV Files in Python

Abdul Daim - Mar 27

History and Features of Python

Dhup Thumbadiya - Mar 12