Different Types of Variables (Data types) in Python


This post discusses Python’s data types. You’ll learn how to represent data in programs with variables.

In Python, a variable is a reserved memory location to store values. In other words, a variable in a Python program gives data to the computer for processing.

Variable names are used to identify the data and allow it to be retrieved from memory. Interestingly, variables need not be declared or defined in advance, like in some other languages. This is one of the reasons why Python is considered an interpreted language as opposed to a compiled one — Python doesn’t need compilation before it can run.

All variable names must start with a letter or an underscore character, such as _var1 = 1. Other than that, there are no explicit rules. You can use letters and digits (including underscore) to form a variable name.

Assigning values to Variables in Python

To assign a value to a variable, you use the equals sign (=).

For example, the following code assigns the value 6 to the variable x:

x = 6

You can also assign values to multiple variables in a single line of code.

For example, the following code assigns the value 6 to the variable x and the value “Hello, world!” to the variable y:

x, y = 6, "Hello, world!"
Code language: JavaScript (javascript)

Remember that Python is case-sensitive, so make sure that you use the exact same casing when you refer to your variables.

For example, if you have assigned a value to a variable named MyVariable, you would refer to it as MyVariable, not as myvariable or MYVARIABLE.

Naming and Using Variables

When using variables in Python, you must follow a few rules and standards. Some of these principles can result in mistakes; others will simply assist you in writing code that is easier to read and understand. When working with variables, keep the following rules in mind:

  • Variable names must contain letters, digits, and underscores. They start with letters or underscores, not numbers. The variable name var_1 is OK, but 1_var is not.
  • Variable names cannot contain spaces, however, underscores can divide words. my_var works, but my var will fail.
  • Python keywords and function names should not be variable names. For example, do not use the word “print” as a variable name.
  • Variable names should be brief but descriptive. For instance, student is better than s, student_name is better than s_n.
  • Variable names are case-sensitive (name, Name, and NAME are three different variables).

Python Strings

Strings contain characters. Python strings are enclosed in single or double quotes:

"This is a string."<br>'This is also a string.'
Code language: JavaScript (javascript)

Changing Case in a String with Methods

You can change a string to all uppercase or all lowercase letters like this:

mystring = "learn PythoN" print(mystring.upper()) #LEARN PYTHON print(mystring.lower()) #learn python print(mystring.title()) #Learn Python
Code language: PHP (php)

Using Variables in Strings

Start a string with f to insert a variable’s value. Wrap any string variables in braces. Python displays each variable’s value.

string_var1 = "learn" string_var2 = "python" string_var = f"{string_var1} {string_var2}" print(string_var) # learn python
Code language: PHP (php)

Adding Whitespace to Strings with Tabs or Newlines

Whitespace in programming includes nonprinting characters like spaces, tabs, and end-of-line symbols.

You can use whitespace to organize your output so that it’s easier for users to read.

Use the characters \t: to add a tab to a string.

Use the characters \n: to add a new line to a string.

print("Python") # Python print("\t Python") # Python print("Languages:\n Python \n Angular \n JavaScript") # Languages: # Python # Angular # JavaScript print("Languages:\n\t Python \n\t Angular \n\t JavaScript") # Languages: # Python # Angular # JavaScript
Code language: PHP (php)

Stripping Whitespace

Extra whitespace can be confusing in your programs. You can easy to eliminate extra whitespace from your string in Python.

To ensure that no whitespace exists:

  • On the right side of a string, use the .rstrip() method.
  • On the left side of a string, use the .lstrip() method
  • From both sides at once use strip() method:
mytring = ' Angular ' print(mytring.rstrip()) # ' Angular' print(mytring.lstrip()) # 'Angular ' print(mytring.strip()) # 'Angular'
Code language: PHP (php)

Remove the Prefix and Suffix from a String in Python

Use the str.removeprefix() and str.removesuffix() methods to remove the prefix and suffix from a string.

# requires Python 3.9+ languages = '$123Python Angular React#456' without_prefix = languages.removeprefix('$123') print(without_prefix) # 'Python Angular React#456' without_suffix = languages.removesuffix('#456') print(without_suffix) # '$123PyThon Angular React' without_prefix_and_suffix = languages.removeprefix('$123').removesuffix('#456') print(without_prefix_and_suffix) # 'Python Angular React'
Code language: PHP (php)

Python Numbers

Python numbers include Integers, floating point, and complex. Python classes include int, float, and complex.

The type() function checks variable data type. Returns variable data type.

a = 6 print(a, "is of type", type(a)) # 6 is of type <class 'int'> a = 6.0 print(a, "is of type", type(a)) # 6.0 is of type <class 'float'> a = 1+2j print(a, "is complex number?", isinstance(1+2j,complex)) # (1+2j) is complex number? True
Code language: PHP (php)

Integers are used to represent whole number values.

You can add (+), subtract (-), multiply (*), and divide (/) integers in Python.

print(1 + 3) # 4 print(5 - 2) # 3 print(5 * 3) # 15 print(3 / 2) # 1.5 #Python uses two multiplication symbols to represent exponents print(3 ** 2) # 9 print(3 ** 3) # 27 a = 5 print(type(a)) # <class 'int'>
Code language: PHP (php)

Float data type is used to represent decimal point values.

A floating-point number is accurate up to 15 decimal places. Integer and floating points are separated by decimal points.

b = 0.343522334567834 print(b) # 0.343522334567834 print(type(b)) # <class 'float'>
Code language: PHP (php)

Complex numbers are used to represent imaginary values. Imaginary values are denoted with ‘j’ at the end of the number.

x = 10 + 5j print(x) # (10+5j) print(type(x)) # <class 'complex'>
Code language: PHP (php)

Boolean output is categorical since it is either true or false.

my_number = 5 > 2 # my_number is the boolean variable print(type(my_number)) # <class 'bool'> print(my_number) #the output will be bool # True
Code language: PHP (php)

Constants

Constant variables have the same value throughout a program. Python has no built-in constant types, although programmers use all capital letters to indicate a variable should be treated as a constant and never changed:

MY_NAME = "James Core" WEIGHT = 50
Code language: JavaScript (javascript)

Comments

Python comments use the hash mark (#). Anything following # in your code is ignored by the Python interpreter.

For example:

# Print programming languages print("Python php React Javascript")
Code language: PHP (php)

Python ignores the first line and executes the second line.

Python php React Javascript

Python List

A list is a set of things in order. It is one of the most common types of data in Python and has a lot of uses. All the things on a list don’t have to be the same type.

It’s pretty simple to declare a list. Items that are separated by commas are put inside brackets [].

x = [2, 2.3, 'Python']
Code language: JavaScript (javascript)

We can take a single item or a range of items from a list using the slicing operator []. In Python, the index starts at 0.

a = [1, 3, 6, 9, 12, 15, 18, 21] print("a[2] = ", a[2]) # a[2] = 6 print("a[0:3] = ", a[0:3]) # a[0:3] = [1, 3, 6] print("a[5:] = ", a[5:]) # a[5:] = [15, 18, 21]
Code language: PHP (php)

Lists can be changed, which means that the values of their parts can be changed.

x = [2, 4, 6] x[2] = 8 print(x) # [2, 4, 8]
Code language: PHP (php)

Python Tuple

Like a list, a tuple is a set of items in the right order. Only one thing is different: tuples can’t be changed. Once a tuple has been made, it can’t be changed.

Tuples are used to protect data from being changed by other people. They are usually faster than lists because they cannot change dynamically.

It is defined within parentheses () where items are separated by commas.

mytuple = (7,'python', 2+5j)
Code language: JavaScript (javascript)

We can use the slicing operator [] to extract items, but we can’t change its value.

mytuple = (7,'python', 2+5j) print("mytuple[1] = ", mytuple[1]) #mytuple[1] = python print("mytuple[0:3] = ", mytuple[0:3]) #mytuple[0:3] = (7, 'python', (2+5j)) # Generates error, Tuples are immutable mytuple[0] = 10 #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #TypeError: 'tuple' object does not support item assignment
Code language: PHP (php)

Python Set

Set is an unordered collection of unique items. Set is made up of values that are separated by commas and put between braces. Items in a set are not ordered.

myset = {6, 2, 8, 1, 0} print("myset = ", myset) # myset = {0, 1, 2, 6, 8} # data type of variable a print(type(myset)) # <class 'set'>
Code language: PHP (php)

On two sets, we can do things like union and intersection. Sets have unique values. They get rid of the same things.

myset = {1,2,2,3,3,3,4,4,4,4} print(myset) # {1, 2, 3, 4}
Code language: PHP (php)

Since sets are not ordered, indexing makes no sense. So, the slicing operator [] doesn’t work.

print(myset[1]) #Error #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #TypeError: 'set' object is not subscriptable
Code language: PHP (php)

Python Dictionary

Dictionary is a set of key-value pairs that are not in any particular order.

It is often used when we have a lot of information. Dictionaries are designed to make it easy to find information. To get the value, we need to know the key.

In Python, dictionaries are defined between braces {}, and each item is a pair with the form key:value. Any kind of key and value can be used.

dict = {2:'value','key':8} print(type(dict)) # <class 'dict'>
Code language: PHP (php)

We use the key to retrieve the respective value. But not the other way around.

dict = {2:'value','key':8} print(type(dict )) #<class 'dict'> print("dict[2] = ", dict[2]) # dict[2] = value print("dict['key'] = ", dict['key']) # dict['key'] = 8 # Generates error print("dict[8] = ", dict[8]) #Traceback (most recent call last): # File "<stdin>", line 1, in <module> #KeyError: 8
Code language: PHP (php)

Conversion between data types

We can change between different kinds of data by using functions like int(), float(), str(), and so on.

#Convert int to float print(float(5)) # 5.0 #Convert float to int print(int(10.6)) # 10 #Convert String to float print(float('2.5')) # 2.5 #Convert int to string print(str(234)) # "234"
Code language: PHP (php)

We can even convert one sequence to another.

print(set([1,2,3])) # Convert list to set # {1, 2, 3} print(tuple({5,6,7})) # Convert set to tuple # (5, 6, 7) print(list('hello')) # convert string to list # ['h', 'e', 'l', 'l', 'o']
Code language: PHP (php)

To convert to a dictionary, each element must be a pair:

# Convert list to dictionary def Convert(lst): res_dct = {lst[i]: lst[i + 1] for i in range(0, len(lst), 2)} return res_dct mylist = ['x', 1, 'y', 2, 'z', 3] print(Convert(mylist)) # {'x': 1, 'y': 2, 'z': 3}
Code language: PHP (php)

Andy Avery

I really enjoy helping people with their tech problems to make life easier, ​and that’s what I’ve been doing professionally for the past decade.

Recent Posts