Python Variables and Data Types
Python Variables and Data Types

Python variables and their data type are essential when writing effective and efficient Python code. By knowing the Python Variables and Data Types, we are able to perform various operations to achieve our desired goals.

A programming variable is defined as a container given a symbolic name that holds a value or data. In another way, the variable declaration is a way of holding a storage position from the memory and naming it.

They are called variables because the data stored there can be changed over time during the code executions. Variables can be stored in various types of data including Numbers (int, float), Strings (text), Boolean (True or False), sequences, and many more. In this article you will learn everything about Python variables and data types.

How to Define and Assign Value to a Variable in Python

Python variables can be defined or declared by stating the name of the variable, the assignment operator (=), and the value you want to store in the variable.

The assignment operator (=) used in programming languages like Python, tells the compiler/interpreter to assign the value that appears on the right-hand side to the variable, which is declared and named on the left-hand side.

In the following example, we create different variables and store different values:


car = 'Toyota'  # the variable name is 'car' and the value type is string
price = 40000   # the variable name is 'price' and the value type is integer
qty = 3         # the variable name is 'qty' and the value type is integer

Note: To declare a variable set of rules have to be followed in order to give a valid name to a variable. Learn more about variable rules in our Python Syntax guide.

In Python, it is not necessary to declare the data type of a variable, and the variable can be assigned to different values at different times. This feature of Python allows the language to automatically determine the data type of the variable based on the value that is assigned to it.

In the following example, we create a variable and give value at different times:


distance = 25   # declare a variable and assign an int value
print(distance) # print the value in the variable

distance = 5.30 # reassign float value to the declared variable
print(distance) # print the value in the variable

The output of the above code reads as follows:


25
5.3

How to Display a Value of a Variable in Python

In Python, you can display or print text on the console using a built-in function called print(). The value you can display is a text or values stored in a variable.

If the value you want to be displayed is text only, the text must be surrounded by quotations (single ” or double “”) and it must be inserted inside the parentheses () .

Consider these syntaxes when using a print() function in Python:

  • If you want to display both text and variables in one print() function, each value must be separated by a comma (,). Example: print("Text value")
  • If the value you want to be displayed is a variable value, you have to mention the variable name inside the parentheses () without a quotation. Example: print(var_name)
  • If you want to display both text and variables in one print() function, each value must be separated by a comma (,). Example: print("Text value one", var_name1, "space", var_name2)

Here are some examples of how to use the print() function in Python:


# How to Display a Value of a Variable in Python
a = 20
b = 8

print("This is a text display")  # display only text
print(a)  # display only one variable
print(a, b)  # display multiple variables
print('The value of a is:', a, 'The value of b is:', b)  # display only text

The output of the above code reads as follows:


This is a text display
20
20 8
The value of a is: 20 The value of b is: 8

How to Assign Multiple Variables to Multiple Values in Python

In the previous section, we explain how to declare and assign a single value, while in this tutorial we explain how to assign multiple variables to multiple values in Python programming. Python allows us to simplify our code and assign multiple values to multiple variables in one line.

For example, you want to declare three variables that can store three different levels of programming skills such as ‘Beginner‘, ‘Intermediate‘, and ‘Advanced‘ levels. Instead of declaring and assigning values in each variable in a separate line, we can use only one line and declare the three variables and assign all their values.

The syntax is as follows: State the three variables separated by a comma (,), then use the assignment operator (=), and finally state the three values separated by a comma.

var1, var2, var3 = 'value of var1', 'value of var2', 'value of var3'

In the following example, we create a variable and give value at different times:


# How to Assign Multiple Variables to Multiple Values in Python
first_level, second_level, third_level = "Beginner", "Intermediate", "Advanced"

# print the three levels of programming skills
print(first_level)
print(second_level)
print(third_level)

The output of the above code reads as follows:


Beginner
Intermediate      
Advanced

Note: It is not necessary for each value to be one data type. you can use strings, integers, floats, etc.

The following example shows different variables that take different value that has different data types, such as string, integer, and float.


# How to Assign Multiple Variables to Multiple Values in Python
student_name, student_age, student_cgpa = "Khan", 12, 4.1

# print the three levels of programming skills
print(student_name)
print(student_age)
print(student_cgpa)

The output of the above code reads as follows:


Khan
12
4.1

Note: The number of variables created must match the number of values assigned otherwise Python will trigger an error look like this “ValueError: not enough values to unpack (expected 4, got 3)“.


# How to Assign Multiple Variables to Multiple Values in Python
student_name, student_age, student_cgpa, student_status = "Khan", 12, 4.1

The output of the above code reads as follows:


Traceback (most recent call last):
  File "e:\variables.py", line 2 , in <module>
    student_name, student_age, student_cgpa, student_status = "Khan", 12, 4.1  
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 4, got 3)

How to Assign Multiple Variables to Single Value in Python

In Python, using only one line of code you can able to assign one value to multiple different variables. This practice simplifies the code and reduces the code complexity as we only consume one line.

The syntax is as follows: All the variables and its value are separated by an assignment operator (=). There is no comma in this syntax.

var1 = var2 = var3 = value

The following Python code assigns a single value to three variables:


# How to Assign Multiple Variables to Single Value in Python
num_one = num_two = num_three = 5

# print their values
print(num_one)
print(num_two)
print(num_three)

The output of the above code reads as follows:


5
5
5

How to Specify a Data Type of a Variable in Python

As we said, in Python, there is no requirement to declare variables with a specific data type, In case it is required, it is possible to specify the kind of data that a variable is intended to hold. However, this process of informing the compiler of the type of data a variable should keep is called casting or typecasting.

The benefit of casting is that it helps that the variable is used correctly throughout the program and to avoid type conflicts.

Here are some examples of how to do casting by specifying the data types for variables:


name = str('Gilbert')    # defined as str
age = int(25)            # defined as int
salary = float(35.60)     # defined as float
is_maried = bool(True)   # defined as bool

How to Know the Data Type of a Variable in Python

In Python, you can know the data type of the variable or the kind of data that is contained using a built-in function called type()  . This Function determines the data type of a variable or the type of data it contains.

The following example shows how to use the type() function to get the data type of a variable:


name = 'Gilbert'
age = 25
salary = 35.60
is_maried = True

print(type(name))       # checks the type of name
print(type(age))        # checks the type of age
print(type(salary))     # checks the type of salary
print(type(is_maried))  # checks the type of is_maried

The output of the above code reads as follows:


<class 'str'>
<class 'int'>
<class 'float'>
<class 'bool'>

Properties of Python Variables

There are several properties or characteristics Python variables have. These properties include

  • Name
  • Assignment Operator
  • Type
  • Value
  • Scope
  • Mutability
  • Location

Variable Name

In Python, every variable must have a name. Therefore, when naming a variable it must be followed a set of rules including it must start with a letter, or underscore (_) and cannot be started with a number. It also cannot contain white spaces or special characters and it must not be any of the reserved keywords in Python. Python variables are also case-sensitive which means 'Name' and 'name' is different. It is recommended every variable have a unique name to avoid confusion and maintainability issues.

Variable Assignment Operator

The other property a Python variable should have is a value. Therefore to assign a value, we must use the assignment operator (=). This means, after naming the variable you must use the assignment operator to store a specific value for a variable. This operator always is in between the name and the value.

Variable Type

Every Python variable has a Data type, therefore, in Python, it is not compulsory to declare variables with a specific data type, but you can still provide the data type of the variable during the declaration, otherwise, it will automatically read from the value stored. for example: name='Deric'. Python automatically recognizes this variable as a string during the runtime.

Python provides several data types including integer, float, string, boolean, set, list, tuple, dictionary, range, bytes, NoneType, and many more.

Variable Value

Python variables must contain a value, in order to be recognized as a variable. Value can be any form of the data types Python supported. It is also notable that variables change over time. For example, variably called temperature was stored for 27. Therefore, from time to time such value can be changed to 29, or any other value according to the changes in the temperature.

Variable Scope

The variable must have a scope that indicates where it can be accessed in the code. This means we can able to control the availability or the accessibility of the variables in certain ranges of the code.

for example, a variable defined in a function that can only be accessed within that function is called a local scope variable while those that are defined outside of a function and can be accessed anywhere in the code are called global scope variables.


a = 30  # global scope variable

# declare a function

def my_fun():
    b = 20  # local scope variable
    print(b)
    print(a)


# call the function
my_fun()
print(a)

# this trigers an error becouse it is local scope variable
# print(b)

The output of the above code reads as follows:


20
30
30

Note: The variable acan be accessed and available anywhere in the code while the bvariable can only be accessed inside the function.

In Python, you can create a variable inside a function and make it global using globalkeyword.

The following example shows how to create a variable inside a function and use it outside the function:


# How to use the global keyword in Python
a = 55  # global scope variable

# declare a function

def my_fun():
    global b  # global scope variable
    b = 30

# call the function
my_fun()
print(a)
print(b)

The output of the above code reads as follows:


55
30

Note: The global variable declaration and assigning it to a value should be in a separate line as shown above, otherwise, it will trigger an error saying “invalid syntax“.


# How to declare and assign value to global variable in one line
def my_fun():
    global b = 30  # global scope variable

# call the function
my_fun()
print(b)

The output of the above code reads as follows:


  File "e:\variables.py", line 80
    global b = 30  # global scope variable
             ^
SyntaxError: invalid syntax

Variable Mutability

Variable mutability refers to the ability to be able to modify their values. In Python, there are several data types that are not mutable such as Tuples and sets and some are mutable such as dictionaries and lists. Mutable means their value can be changed over time while immutable means it cannot be changed after it has been created.

Variable Location

As we mentioned earlier, every variable has a value and type, therefore such data will be stored in a variable or somewhere in the memory and you should not worry about this since Python engines will take care of it.

Therefore, it is necessary to manage this storage as the program code grows over time. Thus, Python has something called garbage collection which manages memory storage. The garbage collections automatically remove the unused variables from the memory in order to save storage space.

What is the Naming Convention for Variables in Python

To make a readable variable you need to follow one of these naming convention techniques as the style of writing. These techniques are used when you want to create a variable with two or more words.

  • Snake Case
  • Camel Case
  • Pascal Case

Snake Case

Snake Case is a naming convention technique used for variables with multiple words. This technique separates each word using underscores (_) and all the words are in lowercase.

The purpose of using the Snake Case technique is to make the variables in the code easier to read and distinguish between words in the variable name. This technique is used when we are dealing with longer and more complex variable names.

Here we show some examples of Snake Case variable names in Python:


# Snake Case
student_first_name = 'Abraham'
student_second_name = 'Lincoln'
student_age = 26
student_cgpa = 3.5

# print their values
print(student_first_name, student_second_name)
print(student_age)
print(student_cgpa)

The output of the above code reads as follows:


Abraham Lincoln
26
3.5

Camel Case

Camel Case is another naming convention technique used for variables containing multiple words. In this technique, the first letter of each word in the variable is capitalized, except for the first word of the variable which is in lowercase. Unlike the previous one Camel Case does not use an underscore (_) sign in between the words.

This technique of naming convention is used to make the variable names easy to read and classify and it is a recommended practice for variables with multiple words.

Here we provide examples of how to make a Camel Case variable in Python:


# Camel Case
studentFirstName = 'Susan'
studentSecondName = 'Connor'
studentAge = 22
studentCgpa = 4.0

# print their values
print(studentFirstName, studentSecondName)
print(studentAge)
print(studentCgpa)

The output of the above code reads as follows:


Susan Connor
22
4.0

Pascal Case

Pascal Case naming convention is also used when we have multiple words in our variable. This technique capitalizes the first letter of each word and does not use underscore (_) as well.

Similar to the previous techniques of naming convention, this technique also makes the variable names easy to read, easy to understand, and easy to classify. Each programmer should use one of these recommended styles when writing variables that contain multiple words.

Here we show some examples of Snake Case variable names in Python:


# Pascal Case
StudentFirstName = 'Ali'
StudentSecondName = 'Sharif'
StudentAge = 25
StudentCgpa = 3.8

# print their values
print(StudentFirstName, StudentSecondName)
print(StudentAge)
print(StudentCgpa)

The output of the above code reads as follows:


Ali Sharif
25
3.8

Conclusion

In this tutorial, the most important concepts of Python variables were explained and demonstrated with examples. This topic has covered everything you need to know about Python variables including how to declare a variable, and how to assign values, we also discussed how to display the variables on the console, different types of data types, and how to check variable data types were also explained.

More importantly, we also discussed variable properties including their names, scope, location, etc. Finally, we described the naming convention for variables in Python such as the Snake Case, Camel Case, and Pascal Case.

This tutorial can assist all levels of Python practitioners as it provides all the essentials of Python variables and make their experiences in Python grow stronger. More discussions related to Python Dataypes can be found here.

Key Terms

Python Variables, Python Data Types, Naming Variables, Defining Variables, Assign Value,  Variable Scope, Output Variables, Casting or Typecasting, Naming Convention, and Practical Examples.

Categorized in: