What are the data types and variables in python?
Table of Contents
What is variable in python?
The variables in python are a reserved memory space to store data or information. It is often described as boxes where you can store values. It’s much better to think of variables as labels that you can assign to values. You can also say that a variable references a certain value.
When you create a variable, you reserve some space in the memory. Therefore, It is like a container for storing data values. Hence, depending on the types of data, variables can store integer, float, or string in it.
For example, let’s try using a variable in blog.py;
website = "www.bhutanpythoncoders.com"
We’ve created a variable named website. This variable is associated with the value “www.bhutanpythoncoders.com” text. And the type of data stored inside the variable is a string; string data types are always enclosed inside the quotation mark. So, to print the value inside the variable, you should pass the variable name inside the print function;
print(website)
So, when you run the program blog.py, you should see the following line of output:
www.bhutanpythoncoders.com
Furthermore, you can also change the value of a variable in your program at any time, and Python will always keep track of its current value. For instance, I am adding the same variable name with a different value in it;
website = "www.bhutanpythoncoders.com"
website = "172.0.0.1"
print(website)
Only the current value is printed.
172.0.0.1
Variable naming rules
- Variable names can contain only letters, numbers, and underscores.
- The variable should be lowercase, with words separated by underscores as necessary to improve readability.
- Avoid using Python keywords and function names as variable names; that is, do not use words that Python has reserved for a particular purpose, such as the word print.
- Variable names should be short but descriptive. For example, the name is better than n, permanent_address is better than p_a.
- Be careful when using the lowercase letter l and the uppercase letter O because they could be confused with the numbers 1 and 0.
- Variable names are case sensitive. In the variable named website; Website and website is two different things.
- Variable can be of any length.
- A variable name can’t begin with a number. For instance, you can call a variable result_2020 but not 2020_result.
- Variable can’t contain only digits or numbers. For instance, you can name a variable as twenty but not 20.
- It can start with an underscore (_). For example, _website.
Assigning values to a variables; simple data types
To assign a value or data to the variable, we have to use an equal sign (=). Consequently, we can assign different types of data to the variable. Simple data types we can assign are string, integer, and float. Since, python being a dynamically typed language, we need not have explicitly mentioned the types of data when assigning to a variable. Python interpreter interprets the data type implicitly interpreting the value. Moreover, there is also a built-in function type and id to check the type of data and memory address in python.
Let’s assign three types of data to a variable;
1. String
A string(str) is a series of characters and anything inside quotes is considered a string in Python. You can use single or double quotes around your strings.
Example:
name = "Dawa" # Variable is name and value is “Dawa”
print(name)
print(type(name)) # Checking data type of name
print(id(name)) # Finding memory address of name
Output:
Dawa
<class 'str'>
1707095278192
2. Integer
Integer(int) is a whole number, positive or negative, without decimals of unlimited length in python 3.
Example:
age = 42 # Variable is age and value is 42
print(age)
print(type(age)) # Checking data type of age
print(id(age)) # Finding memory address of age
Output:
42
<class 'int'>
1407
3. Float
Float or floating numbers are the numbers with decimal points in python.
Example:
PI = 3.14 # Variable is PI and value is 3.14
print(PI)
print(type(PI)) # Checking data type of PI
print(id(PI)) # Finding memory address of PI
Output:
3.14
<class 'float'>
1707092168240
Note;
Variables must be assigned before being referenced. Moreover, you do not need to declare any particular type and can even change the type after they have been set.
Assigning values to multiple variables
Python allows you to assign values to multiple variables in one line:
eng, dzo, math = 45, 67, 89
print(eng) # eng mark
print(dzo) # dzo mark
print(math) # math mark
Output:
45
67
89
You can assign the same value to multiple variables in one line:
eng=dzo=math = 50
print(eng)
print(dzo)
print(math)
Output:
50
50
50
You can also use the + operator to add a variable to another variable and to add an integer value. It works as a mathematical operator.
Example 1:
name = " Pema"
greeting = "Welcome"
message = greeting + name
print(message)
Output:
Welcome Pema
Example 2:
math = 50
Eng = 70
Total = math + Eng
print(Total)
Output:
120
You can concatenate a string and add two numbers but not string and number together. Python gives you a TypeError.
name = "Pema"
math = 50
print(name + math)
Error message:
line 3, in <module>
print(name + math)
TypeError: can only concatenate str (not "int") to str
Swapping variables in python
One of the good features of a python programming language is to swap a variable easily. We can swap a variable without the involvement of a temporary third variable. Syntax: a, b = b, a where a and b is a variable name.
Example:
num1 = 100
num2 = 200
print("Before swapping a variable")
print(f"num1: {num1}")
print(f"num2: {num2}")
# Swapping a variable
num1, num2 = num2, num1
print("After swapping a variable")
print(f"num1: {num1}")
print(f"num2: {num2}")
Output:
Before swapping a variable
num1: 100
num2: 200
After swapping a variable
num1: 200
num2: 100
Avoiding name errors when using variables
Every programmer makes mistakes and good programmers know how to respond to those errors efficiently. Let’s write some code that generates an error. Enter the following code, including the misspelled word gretings;
greetings = "Good morning!"
print(gretings)
Error message:
line 2, in <module>
print(gretings)
NameError: name 'gretings' is not defined
The program generated some error messages.
When an error occurs in your program, the Python interpreter does its best to help you figure out where the problem is. The interpreter provides a traceback when a program cannot run successfully. A traceback is a record of where the interpreter ran into trouble when trying to execute your code. The error message, “NameError: name ‘gretings’ is not defined” has been traced by the interpreter at line 2 after you’ve accidentally misspelled a variable’s name. Therefore, you should know that programming languages are strict and case sensitive, despite being disregard for good and bad spellings.
Deleting a variable
Variables in python can be deleted using the keyword del. Once the variable is deleted, you can’t access it again, it will give a NameError.
name = "Sonam"
print(name)
del name # Variable name deleted
print(name)
Output:
Sonam
Traceback (most recent call last):
File "C:/Users/Dawa/main.py", line 5, in <module>
print(name)
NameError: name 'name' is not defined
Global and Local variables in python
- Variables that are defined outside of a function are known as global variables. It can be referenced everywhere in a program, inside as well as outside of the function.
- Local variables are the variables defined inside the functions. It can be referenced only inside a particular function.
- However, using the keyword global, you can reference the local variable outside the function.
Example:
age = 45 # Global variable
def variable_scope():
global name # name declared globally
name = 'Pema' # Local variable
print("Local variable name =", name)
variable_scope()
print("Global variable age =", age)
print("Name accessing outside the function:", name)
Output:
Local variable name = Pema
Global variable age = 45
Name accessing outside the function: Pema
Summary
- Variables are used to store any values
- Values can be of any type; string, integer, and float
- Variables are case sensitive
- Assigning multiple values to multiple variables is possible
- Similarly, assigning the same value to multiple variables is also possible
- Swapping a variable in python is easy
- You can delete a variable by keyword del
- There are a so-called Global and Local variables based on their scope of reference in the program
Related article: Identifiers and Keywords in python