Python Variables and Types

Updated 11 September 2020

Continuing our Python journey deeper into this dynamo of a programming language we will take a leap into variables and types. Variables are one of the most fundamental concepts and exist in pretty much all programming languages. Variables are by no means specific to just the language of Python and they will certainly be required in most of your programming escapades. Python provides a simple and dynamic way to create variables in your code, yet it maintains a powerful type categorisation system to ensure safe operations with your data.

This guide will provide a complete understanding of what a variable is inside the Python programming language. Furthermore, it will clarify every variable type and outline how they can be useful in your coding ventures. Contents of this guide can be seen below.

There are several related tutorials on our website to help you become a true Pythonista. A great place to start would be Python Rundown and Main Windows. This will also tell you where to download Python and access online Python emulators. Python is an excellent language to utilise with Raspberry Pi Boards such as Raspberry Pi 4 Model B 8GB. These are computing devices that can easily fit on the palm of your hand.

Making captivating and rare code is just moments of conception away. As always if you have any questions, queries or things to add please let us know your thoughts!


Overview of Variables

Variables are just a method to temporarily store data in a computer’s memory.  A variable is created the moment you first assign a value to it. The equal sign | = | is used to assign a value to a label which creates in Python a variable. Imagine variables as a box filled with books with a label slapped onto the outside of the box. These books can be changed, replaced, and/or altered at any point.

You can use the label to access the data within the variable anywhere within your program. It is best practice to give your identifiers, the title of the variable, a name that makes sense. Python is a case-sensitive language. This means if you type | X = 1 | and | x  = 2 | in your code Python will record and store two unique variables into the memory. Every variable in Python must have an identifier which can consist of letters, numbers, and/or the underscore character. Variables do not need to be declared with any type and can even have their type changed after the variable have been set.

Seen below is an example of a Variable with identifier | X | which has been established in Python. This variable below is the answer to life, the universe and everything.

This file denotes a variable. 7.5 million years of calculation later!

When it comes to naming variables do not be afraid of using longhand and avoiding abbreviation as it will be easier to figure out what is going on in your code after a long period away from the computer screen. When writing longhand identifiers you can use underscores to separate words.


Variable Types

There is a huge variety of data types which Python can use and create variables from. Different data types allow you to do different things to the data whilst maintaining safe operation. Python will track the value of a variable, letting you access it via the identifier, and it will also track the type of the value assigned to a variable.

Now it is useful to know that variables do not need to be manually declared with any kind of variable type. To figure out what the type a variable is you can use the | type() | function in the Python Shell Window and by typing the associated indicator inside the brackets. This function is installed by default into Python. Below is a list of every single Python variable types built into the programming language.
 
Tube Bro


Text

          -      String Literal Type referred in code as | str |

This is how to get words and text into your code. In Python, as well as numerous other programming languages, a string is a sequence of characters or a single character. The term literal refers to a specific value or a fixed value or a constant that is used within the program. Within Python, the literal value of a string (a string literal) is the value surrounded by either single quotation marks or double quotation marks. In Python language, there is no character data type, so all single characters are also referred to as strings with a length of one.

Some characters and symbols have special meaning and cause processes to run when code is executed in Python. This can be a problem if you just wanted to display this character inside a string. Within Python, some special characters are newline, backslash | \ | or quotes | ’ ‘ |. The effects that these characters do may not be desired, but you may want to record the character in a String Literal. To use these in a string literal without triggering the special processes use backslash | \ | followed directly by the desired character. An example of a string literal variable with a quote can be seen below.

X is a string literal variable. Input on top, Output on Bottom


Boolean

          -      Boolean Type referred in code as | bool |

In computer science, the Boolean data type is a type which has one of two possible values. The intent is to represent the truth values of logic. This simply means determining whether a proposed statement is truthful or a falsity. The Boolean name comes from the man who first defined algebraic system of logic, George Boole.

In programming, you often need to know if an expression is True or False. In Python, the recorded data for this fact would be a Boolean type. Make sure to use capital letters for a Boolean variable. Other Boolean data would be Yes or No however this is not used in Python. You can use | bool() | to evaluate any expression in Python. This will feed back one of two answers, True or False. Below is an example of Boolean type variables being set up in Python. 

making a Boolean type data, Shell output underneath

 

There are also Boolean expressions within Python. This is an expression that evaluates to produce a result which is either True or False by using a comparison operator. Below is an example of a Boolean comparison operator being used in the Python Shell.

Boolean comparison operator

 

The double equal sign | == | is referred to as a comparison operator. Worth noting a single equal sign | = | is an assignment operator. Examples of all Boolean comparison operators are below.
Comparison Operators


Numeric

          -      Integer Type referred in code as | int |

For a variable to be an integer the data must be a single whole number. It can be of unlimited length. Furthermore, it must be a positive or negative number and it must not have a decimal or fractional component. Python and many other programming languages will store numbers automatically as an integer so long as it fits the above criteria. If your using Python 2 the integer will not be of unlimited length and you will need to use a different variable type called | Long | to write large integer sizes. In the most modern Python version length of the integer variable is unlimited. Below is an example of making an integer type variable.

This file makes an integer variable, output below

 

          -      Float Type referred in code as | float |

Float is also referred to as a floating-point number. It must be a positive or negative number and contain a decimal or fractional component. It can be of unlimited length. Float numbers also encapsulate scientific numbers. Within Python, the character | e | is used to denote the power of 10. Below is an example of making a float type variable.

 This file makes a float variable, output below

          -      Complex Type referred in code as | complex |

Complex numbers are useful abstract quantities that can be used in calculations and result in physically meaningful solutions. Complex numbers are written in the form | A + Bj |, where A and B are real numbers and j is the square root of -1. Not used very often in Python programmes but they will come up if you start diving into Fourier transforms or fractals such as the Mandelbrot set. Below is an example of making a complex type variable.

This file makes a complex variable, output below


Sequence

          -      List Type referred in code as | list |

A variable will be a list type if the data is a collection which is both ordered and changeable. It must also allow duplicate data members. A member (or element) is a distinct and individual object within the collection of objects. Lists are very similar to arrays. An array is an arrangement of objects, pictures, or numbers in columns and rows. In Python, list type data can contain any type and combination of variable such as a string numerical and Boolean variable. They can also contain as many variable members as you wish. Within Python, lists are written with square brackets and can be iterated over simply. To access an item in a list we can use the index operator | [ ] |. Indexing starts at 0 then 1 then 2 for each subsequent member. Below is an example of how to build a list variable and how to pull out and print an item in the list.

List with mixed data types and Output of code on bottom 

          -      Tuple Type referred in code as | tuple |

A variable will be a tuple type if the data is a collection which is both ordered and unchangeable. It must also allow duplicate members. In Python, tuples are written with round brackets and cannot be iterated over simply. Once a tuple is created, you cannot change its values. Tuples are immutable. In object-oriented and functional programming, such as Python, an immutable object is an object whose state cannot be modified after it is created. But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple. Look at the bottom of this page to learn how to do this under Assigning a Type to a Variable. To access an item in a tuple we can use the index operator | [ ] |. Indexing starts at 0 then 1 then 2 for each subsequent member. Below is an example of making a tuple variable and displaying the contents of the data.

Making a Tuple variable with Output on the bottom

 

          -      Range Type referred in code as | range |

Objects/variables of the range type are created using the | range() | function. This type does not support slicing, concatenation or repetition. These are all fundamental string operations that will be explored in further tutorials. The range function is a good tool to produce iterables that yield arithmetic progressions. The results will always be integer numbers. An iterable is any Python object capable of returning its members one at a time, permitting it to be iterated over in a for-loop. Syntax of range, when written in Python, is as follow | range([start,] stop [, step]) |. Some examples of this function can be seen below.

Range Variable Example 1, Shell Output on bottom

 

Range Variable Example 2, Shell Output on bottom

 

Range Variable Example 3, Shell Output on bottom


Set

          -      Set Type referred in code as | set |

A variable will be a set type if the data is a collection which is both unordered and unindexed. It must also not allow duplicate members. Therefore, every piece of data inside a set is unique. In Python, sets are written with curly brackets and can be iterated over. This data type is mutable and thus can be modified after it is created. When you print a set, you can never be sure in which order the items will appear as the set is unordered. This also means there is no indexing with set type data. See below an example of a set variable being created.

This makes a set, Output on bottom

 

          -      Frozen Set Type referred in code as | frozenset |

The frozen set is simply an immutable version of a Python set. Thus, a variable will be a frozen set type if the data is a collection which is immutable, unordered and unindexed. It must also not allow duplicate members. Therefore, every piece of data inside a frozen set is unique. In Python frozen sets are written with | frozenset() | function. Data can be stored in memory using curly brackets inside this function. It cannot be iterated over. This data type is immutable and thus cannot be modified after it is created. When you print a frozen set, you can never be sure in which order the items will appear as the frozen set is unordered. This also means there is no indexing with frozen set type data.  Frozen sets can be used as keys in Dictionary, a variable type seen lower in the page, or as elements of another set. See below for an example of a frozen set variable being created.

This makes a frozen set, Output on bottom


Mapping

          -      Dictionary Type referred in code as | dict |

A dictionary variable is a collection of data which is unordered, changeable, and indexed. It also will not have any duplicate members. In Python, dictionaries are written with curly brackets with elements separated by commas. Each member will have a key and value. This is expressed as a pair | key:value |. The values can be of any data type and can repeat. Keys must be immutable (unchangeable) and must be unique. This is important to allow indexing of the data in the dictionary variable. This data type is often referred to as associative memories or associative arrays in other programming languages.


Binary

Tube GalThis section on binary explains variable types rarely interacted with for most users of Python. These variable types are Python attempting to give the user low-level code functionality. This is for people who want their code to run at a higher speed. An example of low-level programming language would be C and machine code. Binary types remove some of the abstraction between what the computer is doing versus the human-written code. A byte is a unit of digital information that most commonly consists of eight bits. The byte originally was the number of bits used to encode a single character of text in a computer. For this reason, it is the smallest addressable unit of memory in most computers.
 

          -      Bytes Type referred in code as | bytes |

A variable is a bytes type if the data is immutable (thus unchangeable) and is a sequence of single bytes. Many major binary protocols are based on the ASCII text encoding. ASCII is the American Standard Code for Information Interchange and is a character encoding standard for electronic communication. Bytes objects offer several methods that are only valid when working with ASCII compatible data. In a variety of ways, bytes type variables are closely related to string objects. The | bytes() | function will return a bytes object. The immutable sequence will be integers in the range of 0 to 255.

 

          -      Bytes Array Type referred in code as | bytearray |

Bytes array is simply a mutable version of a byte set. If you want to change or alter your byte data after it has been created in the code, then you will use byte array type variable. The | bytearray() | function will return a bytes array object. The mutable sequence will be integers in the range of 0 to 255.

 

          -      Memory-View Type referred in code as | memoryview |

Now, this is a variable type that is very rarely used and is a superb example of Python giving the user the potential for low-level functionality. Within Python, to access this type use the | memoryview() | function. The definition of memory-view type variables is as follows, memory-view variables allow Python code to access the internal data of an object that supports the buffer protocol without copying. So, breaking this down. Buffer Protocol is a protocol which allows the computer to talk directly to a binary data structure. This really means this will shortcut working at an object level and instead work at a lower-level (like the programming language C). This will allow you to get to information really fast and not have to copy the entire file to get the information desired. This makes the program use less memory and increases the execution speed. Only two variable types work with this function and they are bytes and bytes array variables.  


Assigning a Type to a Variable

If you want to specify the variable type you can use constructor functions in your code as you can see below. It is worth noting that when creating a variable, it is not necessary to specify the type although if you do you will reap more control over your code.
 

Assigning a type to a variable


The Next Step

A great next step on your coding adventures would be the guide All the Keywords in Python.
 


Have a question? Ask the Author of this guide today!

Please enter minimum 20 characters

Your comment will be posted (automatically) on our Support Forum which is publicly accessible. Don't enter private information, such as your phone number.

Expect a quick reply during business hours, many of us check-in over the weekend as well.

Comments


Loading...
Feedback

Please continue if you would like to leave feedback for any of these topics:

  • Website features/issues
  • Content errors/improvements
  • Missing products/categories
  • Product assignments to categories
  • Search results relevance

For all other inquiries (orders status, stock levels, etc), please contact our support team for quick assistance.

Note: click continue and a draft email will be opened to edit. If you don't have an email client on your device, then send a message via the chat icon on the bottom left of our website.

Makers love reviews as much as you do, please follow this link to review the products you have purchased.