Python Variables - Constant, Global & Static Variables

Tutorial Playlist

In Python, variables are used to name the memory location where data is stored.  The variable is the name of the memory location where data is stored. Once a variable is stored, space is allocated in memory. It defines a variable using a combination of numbers, letters, and the underscore character.

Table of Contents:

In this article,  we will learn all about variables in Python. Following is the list of all topics that we are going to cover in this article:

What is a Variable in Python?

In Python, variables are containers for storing data values. They are created when you assign a value to them and do not need an explicit declaration of their type.

Eg:

# variable ‘num’ stores the integer value 35453
num  = 35453

# variable ‘name’ stores the string value “intellipaat”
name= “intellipaat”

Rules for Naming Variables in Python

Some naming conventions must be followed to name Python variables:

  • The name of a variable cannot start with a digit. It should start either with an alphabet or the underscore character.
  • The name of the variables can only contain digits, letters, and an underscore(_).
  • Python variables are case-sensitive, which means name and Name will be treated differently.
  • The name of the variables should not contain any reserved keywords like(for, if, else, class, etc.)

1. Valid Python Variables name:

num=34
Product_name=”Intellipaatj”
Product_Carts=[“Shirts”.“Jeans”,”Oil”]

2. Invalid Python Variables name:

2num= 34   # Invalid name because we can’t start with a digit. 
for=”Raj”   #invalid because for is a reserved keyword.
Val-2= 89  #Invalid because - can not used in the name of the variable.
Master Python Programming!
Learn, code, and create with Python. Start now!
quiz-icon

Assigning Values to Variables

Python variables are always assigned using the equal sign (=), followed by the value of the variable. Python also does not require you to specify the data type of the variable, unlike other commonly used programming languages.

1. Basic Assignment

There is no need for an explicit declaration to reserve memory. The assignment is done using the equal sign (=) operator.

Example:

a = 10
b = “Intellipaat”
print (a) # a is an int type variable because it has an int value in it
print (b) # b is a string type variable as it has a string value in it

2. Dynamic Nature of Python

Python is a dynamically typed language, i.e., it automatically detects the type of the assigned variable.

Example :

test = 15
test1 = ”String”

Multiple Variable Assignment

In Python, we can assign multiple variables to a single value or maybe with different values.

1. Multiple Variable Assignment with the same value

We can assign a single value to multiple variables in the following manner:

a = b = c = 5
print(a, b, c)

Output: 5 5 5

2. Multiple Variable Assignment with different value

Also, we can assign multiple values to multiple variables in the following manner:

a, b, c = 2, 25, ‘abc’
print(a, b, c)

Output: 2, 25, abc

Casting a Variable

When we convert a value from one data type into another data type, this process is called casting a variable. In Python, there are a lot of functions for casting a variable.

Eg: including int(), float() and str() etc.

Basic Casting Functions

  • int(): it converts the given value into an integer.
  • float(): It converts the given value into float or decimal.
  • str(): It converts the given value into a string.

Example:

a = "100"
num = int(a)  # converts into integer

b = 23
num2 = float(b)   # converts into float

c = 25
num3 = str(c)  # converts into string

print(num) 
print(num2) 
print(num3)

Output:
100
23.0
25

Getting the Type of Variable

In Python, you can get the data type of a variable with the ‘type()’ function in the following manner:

a = 2
b = "Python"

print(type(a))
print(type(b))

Output:

<class ‘int’>
<class ‘str’>

Scope of a Variable

Not all variables in Python may be accessible at all locations. This depends on where these variables were declared. The scope of the variable defines where, in the program, the variable will be accessible. The scope can be either local or global. So, let’s learn about local and global variables in Python.

1. Local Variables in Python

A variable that is declared inside a Python function or module can only be used in that specific function or Python Module. This kind of variable is known as a local variable.

Example:

a=100
print (a)

def some_function():
   a = ‘Intellipaat’
   print(a)
some_function()
print(a)

Output:
100
Intellipaat
100

In this example, when the variable a is declared the second time inside the function named some_function, it becomes a local variable. Now, if we use that variable inside the function, there will be no issues, as we can see in the output of the second print(a); it prints the value assigned to an in the function, that is, “Intellipaat”.

Whereas, when we try to print the value outside the function, it prints the value assigned to it outside the function, as we can see in the output of the first and third print(a); it prints 100.

2. Global Variables in Python

On the other hand, Python global variables are variables that can be used anywhere within your program without needing to be declared every time they are needed.

Example:

a = 100
print (a)

def some_function():
   global a
   print (a)
   a = ‘Intellipaat’
some_function()
print (a)

Output:
100
100
Intellipaat

Here, in this example, we have declared variable a as a global variable and changed its value inside of a function while printing outside of it; it will print its changed value, as can be seen from print(a). Since variable a was declared globally, it can also be used outside its function scope.

Constants in Python

A constant is a type of variable that holds values that cannot be changed. In reality, we rarely use constants in Python. Constants are usually declared and assigned to a different module/file.

Example:

#Declare constants in a separate file called constant.py
PI = 3.14
GRAVITY = 9.8

Then, they are imported to the main file.

#inside main.py we import the constants
import constant
print(constant.PI)
print(constant.GRAVITY)

Python Class Variables

In Python, a class variable is shared by all the object instances of the class. They are declared when the class is constructed and not in any of the methods of the class. Since in Python, these class variables are owned by the class itself, they are shared by all instances of that class.

class languages:
lang_name = “python”
Here, the variable lang_name is given the value “python”.

Python Private Variables

In Python, ‘Private’ instance variables can’t be accessed except inside an object; they do not practically exist. However, most Python coders use two underscores at the beginning of any variable or method to make it private.

A variable __intellipaat will be treated as a non-public or a private variable.

Object Reference in Python

In Python, an object reference is a variable that stores the address of an object rather than the actual object itself. When we create a variable and assign it an object, the variable becomes a reference to that object.

Let’s understand this with a real-life example:

Suppose we declare a variable as a=100 in Python,

a=100

Python generates an object to represent the value 100 when a = 100 is executed and references this object.

Now, if we want to assign b = a,

Now, b is also pointing to the same reference as a, this is called the shared reference.

If we assign a = 50, and b= 40

Explanation:

Now, a is referencing 50, b is referencing 40, and 100 is no longer referencing any variable, and becomes eligible for garbage collection.

Delete a Variable Using del Keyword

Python provides a feature to delete a variable when it is not in use, so as to free up space. Using the command del ‘variable name’, we can delete any specific variable.

Learn Python, Shape Your Future!
Enroll now and start coding your way to success with Python!
quiz-icon

Example:

a = 10
print (a)
del a
print (a)

If we run the above program, the Python interpreter will throw an error as ‘NameError: name a is not defined’ in the second print (a) since we have deleted the variable a using the del command.

Key Takeaways:

  • Python variables store references to objects rather than the actual themselves.
  • If a variable is not specifically modified, it has no effect on other variables that reference the same object.

Some Practical Examples of Python Variables:

1. Adding two numbers

We can use the + operator, we can add two numbers in Python.

a = 2
b = 5
print(a+b)

Output: 7

2. Find the Maximum of two numbers in Python

We can use the max() function to find the maximum of two numbers in Python.

a = 2
b = 5
print(max(a, b))

Output: 5

3. Count characters  of a String

We can use len() function to count characters in a String.

a = "Intellipaat"
print( len(a))

Output: 11

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

Since we come to the end of the tutorial, we can conclude that the variable types in Python like constants, global, and static are some of the fundamental and yet important parts of coding effectively. It is very important to understand the core functionality of constants and the way it provide a way to declare values that should be changed in the entire program, which helps to avoid accidental modifications.

Global variables allow us to get the across function on the other hand static variables maintain their state within a class context. With the help of variables and proper usage of variables, developers can write very clean yet effective code that can be easily maintained and can follow the best practices in Python.

You can master these concepts by just enrolling in Intellipaat’s Python Programming Course and taking a leap into the new growing world of programming.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 14th Jan 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.