Home > Courses > Python > Introduction to Python

Python variables and data types

Last updated : 21 December 2020

In the previous chapter, we learned about the Python language, the history of Python, and how to set up your work environment to get started with Python. In case if you missed it, take a look at How to start with python programming.

In this chapter, we will learn about variables and data types.

What is a variable?

Variables are containers to hold data that we need in our program. If you are new to programming, think about your kitchen pantry. You may likely have your spices in containers with labels attached. So you know where to find salt and pepper and how to distinguish sugar from salt. In the programming world, a variable is a memory location in your computer that holds a piece of data. To make it easy for us to access that piece of data, we give that memory location a temporary name, so later we can access the data to do manipulations. That is a variable. It is similar to storing pepper in a container. We take a container, stick a label with Pepper written and store pepper in it.

How to create a variable?

Now let us assume we have to store a customer's name and order number in our program. Fire up your IDLE Python console and enter the below code.

>>> customerName = 'John Doe'
>>> orderNumber = 12200

In the above code, we took a memory location in your computer, labeled it customerName, and stored John Doe in that location. The same applies to the orderNumber. Notice the quotation marks I added around the customerName variable. This signals the interpreter that the content between those quotes is not code. It is text or string that I want to output. These can be single or double-quotes. To ensure our data is stored properly, try out these commands to print the content of variables.

>>> print (customerName)
John Doe
>>> print (orderNumber)

Alternatively, you can declare and initialize both variables in a single line.

>>> customerName, orderNumber = 'John Doe', 12200

Variable naming rules

Every programming language has its own rules for the names you are allowed to use. The rules for naming your Python variables can be summarized as follows:

  • Variable names are case-sensitive. CustomerName and customerName are not the same.
  • Variable names can only contain alphanumeric characters and underscore. The variable name should always start with a character (a-z or A-Z) or underscore. It cannot start with a number.
  • Keywords cannot be used as variable names. For example, reserved keywords such as and, as, print, have pre-assigned meanings in Python and are not allowed to use as variable names.

Variable naming conventions

Naming conventions are widely adopted best practices. They are not parsed or validated by the Python interpreter.

  • Camel case notation is the concept of naming variables without spaces or punctuation. The separation of words is indicated with a capitalized letter. We will be using this notation throughout this course to name variables. Ex customerName
  • Use underscore to separate words in a variable. Ex customer_name

Arithmatic operations

We can perform a number of assignment and arithmetic operations on variables.

>>> x,y =2,3

To add two numbers

>>> print (x + y)

To subtract

>>> print (y - x)

To multiply

>>> print (x * y)

To devide

>>> print (y / x)


>>> print (y // x)


>>> print (y % x)

Exponent (x to the power y)

>>> print (x ** y)


Write a program to swap values of two numeric variables without involving a third variable. Lets assume our variables are x and y.

>>> x=2
>>> y=3
>>> print (x)
>>> print (y)

Since we cannot involve aditional variables, the solution is to swap the values by assigning the total to one variable and negating the other variable value.

>>> y=y+x
>>> x=y-x
>>> y=y-x
>>> print (x)
>>> print (y)

Data types

The data type is the type of data that a variable stores. In Python, the data type is determined at the time of the assignment.

Numeric Types

There are mainly three numeric data types. They are int, float, and complex. Integer data type represents whole numbers, such as 2, 24, 5, -4, -100.

>>> x=-100
>>> print (type(x))
<class 'int'>

Complex numbers consist of real and imaginary numbers.

>>> x = 1j
>>> print (type(x))
<class 'complex'>

Float data type represents numbers with decimal points, such as 0.24, 1.456, 100.24.

>>> x=100.24
>>> print (type(x))
<class 'float'>

Text data type

String data type represents characters or text values, such as 'John Doe', 'Python', '1250.00'. Note that the number 1250.00 is enclosed in quotes, which means it represents the text 1250.00

>>> x='John Doe'
>>> print (type(x))
<class 'str'>
>>> x='1250.00'
>>> print (type(x))
<class 'str'>

Sequence Types

There are mainly three sequence data types. They are list, tuple, and range.

List data type

List data type stores data in a one-dimensional row. The stored data can be accessed by the index. The list can hold a collection of ordered arbitrary objects. You can create a list of objects that belong to different data types.

>>> x = ["Java", "C++", "Python", 1.24, false]
>>> print (type(x))
<class 'list'>

The order of the elements in the list is significant. Lists that contain the same elements in a different order are not equal.

>>> x = ["Java", "C++", "Python"]
>>> y = ["C++", "Java", "Python"]
>>> z = ["Java", "C++", "Python"]
>>> x==y
>>> x==z

You can use the elements position/index to access data stored in a list.

>>> x = ["Java", "C++", "Python"]
>>> x[0]

We can use slice to retrieve a segment of the list. In the below example, x[3:5] means we consider items at and between index 3 and index 5-1. This is called the slice notation. In slice notation, the start index is always included and the end index is always excluded.

>>> x = ["Java", "C++", "Python", "JavaScript", "SQL", "Spring"]
>>> x[3:5]
['JavaScript', 'SQL']

To reverse the order of elements:

>>> x = ["Java", "C++", "Python", "JavaScript", "SQL", "Spring"]
>>> x[::-1]
['Spring', 'SQL', 'JavaScript', 'Python', 'C++', 'Java']

Finding elements in a list:

>>> x = ["Java", "C++", "Python", "JavaScript", "SQL", "Spring"]
>>> "Java" in x
>>> "Jquery" in x

To append or concatonate to an existing list

>>> x = ["Java", "C++", "Python", "JavaScript", "SQL", "Spring"]
>>> x + ["Jquery"]
['Java', 'C++', 'Python', 'JavaScript', 'SQL', 'Spring', 'Jquery']

Use del to delete an element.

>>> x = ["Java", "C++", "Python", "JavaScript", "SQL", "Spring"]
>>> del x[4]
>>> x
['Java', 'C++', 'Python', 'JavaScript', 'Spring']

List has build in len(), min(), and max() functions:

>>> x = ["Java", "C++", "Python", "JavaScript", "SQL", "Spring"]
>>> len(x)
>>> min(x)
>>> max(x)

Note that min and max are not based on index. They operate on the actual sort order of list elements. Lists can be nested, meaning one list's element can be another list.

>>> x = ["Java", "C++", "Python", "SQL", "Spring"]
>>> y = ["JavaScript", "Jquery", x]
>>> print(y)
['JavaScript', 'Jquery', ['Java', 'C++', 'Python', 'SQL', 'Spring']]
>>> print(y[2])
['Java', 'C++', 'Python', 'SQL', 'Spring']

Lists are mutable.

>>> x = ['Java', 'C++', 'Python', 'JavaScript', 'SQL', 'Spring', 'Jquery']
>>> x[6] = "React JS"
>>> x
['Java', 'C++', 'Python', 'JavaScript', 'SQL', 'Spring', 'React JS']

Lists Are Dynamic. Lists can grow or shrink when elements are added or removed from the list.

Tuple data type

The tuple is an ordered collection of objects. Tuples are similar to lists in many ways except, tuples are immutable and defined with enclosing parenthesis instead of square brackets.

Everything we have learned about lists is applicable to tuples with the exception of modifications. Unlike lists, tuples are immutable, and cannot be modified after initializing the variable.

>>> x = ('Java', 'C++', 'Python', 'JavaScript', 'SQL', 'Spring', 'Jquery')
>>> x[1] = "C"
Traceback (most recent call last):
  File "", line 1, in 
    x[1] = "C"
TypeError: 'tuple' object does not support item assignment

Dict data type

Dict stands for the dictionary, a collection of key-value pairs. Each key maps to its associated value. Dict is somewhat similar to the list data type. They both are mutable, dynamic, and can be nested. One of the differences is that dictionary elements are accessed by their keys while list elements are accessed by their indexes.

>>> dict = {"Laptop": "$650", "Desktop": "$500", "Tablet": "$350", "Kindle": "$100"}
>>> type(dict)
<class 'dict'>
>>> dict["Laptop"]

To add a new entry

>>> dict = {"Laptop": "$650", "Desktop": "$500", "Tablet": "$350", "Kindle": "$100"}
>>> dict["Router"] = "$50"
>>> dict
{'Laptop': '$650', 'Desktop': '$500', 'Tablet': '$350', 'Kindle': '$100', 'Router': '$50'}

To delete an entry

>>> del dict["Router"]
>>> dict
{'Laptop': '$650', 'Desktop': '$500', 'Tablet': '$350', 'Kindle': '$100'}

Set and frozenset data type

Set is an unordered collection of unique objects.

>>> set = {1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 6}
>>> type(set)
<class 'set'>
>>> set
{1, 2, 3, 4, 5, 6}

Frozenset takes an iteratable object as input and returns an immutable frozenset object.

>>> x = frozenset({"Laptop", "Desktop", "Tablet", "Kindle"})
>>> type(x)
<class 'frozenset'>

Typecasting in Python

Typecasting is converting one data type to another. For example, int to string, float to int, string to float, and so on.

Python provides three ready to use functions to support typecasting. They are int(), str(), and float().

Converting from float to int

Since int supports only whole numbers, the decimal values are discarded.

>>> price = 99.97
>>> int(price)

Str to int

When you convert from str to int, your str value must be a valid whole number. String values like "99.97" or "ninety-nine" cannot be converted to int.

>>> price = "99"
>>> int(price)

int to float

>>> number = 100
>>> float(number)

str to float

Note that when you convert from string to float, unlike string to int, the string value can be any valid float number.

>>> price = "99.97"
>>> float(price)

int to str

Any valid int can be converted to a string.

>>> number = 100
>>> str(number)

float to str

Any valid float can be converted to a string.

>>> price = 99.9797
>>> str(price)
By: Lance
Lance is a software engineer with over 15 years of experience in full-stack software development.

Comments are disabled

No Comments