Python variables and data types

Last updated : Jul 30, 2023 12:00 AM

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. If you missed it, 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?

Let's assume we must 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. That 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 see how our data is stored, try out these commands to print the content of variables.

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

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

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

Variable naming rules

Every programming language has 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 begin with a number.

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 several assignments and arithmetic operations on variables.

>>> x,y =2,3

To add two numbers

>>> print (x + y)
5

To subtract

>>> print (y - x)
1

To multiply

>>> print (x * y)
6

To devide

>>> print (y / x)
1.5

Floor

>>> print (y // x)
1

Modulus

>>> print (y % x)
1

Exponent (x to the power y)

>>> print (x ** y)
8

Quiz

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

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

Since we cannot involve additional 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)
3
>>> print (y)
2

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))

Complex numbers consist of real and imaginary numbers.

>>> x = 1j
>>> print (type(x))

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

>>> x=100.24
>>> print (type(x))

Text data type

String data type represents characters or text values, such as 'John Doe', 'Python', and '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))

>>> x='1250.00'
>>> print (type(x))

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))

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
False
>>> x==z
True

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

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

We can use the slice notation 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. That 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
True
>>> "Jquery" in x
False

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)
6
>>> min(x)
'C++'
>>> max(x)
'Spring'

Note that min and max are not based on the 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 applies to tuples, except for 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"]
'$650'

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 iterable 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)
99

Str to int

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

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

int to float

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

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)
99.97

int to str

Any valid int can be converted to a string.

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

float to str

Any valid float can be converted to a string.

>>> price = 99.9797
>>> str(price)
'99.9797'
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...