Python is a versatile programming language known for its readability and simplicity. Like most programming languages, it uses variables. Variables are essentially containers that hold data, and they play a fundamental role in Python programming. They allow developers to store and manipulate data. In this article, we will explore Variables in Python.
What is a Variable?
In Python languages, a variable is the name of an identifier that stores the value. This value can be of various data types, such as integers, floating-point numbers, string lists, dictionaries and more. Variables act as placeholders for data that can be used and manipulated throughout your program in python language.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
Declaring and Assigning Variables
In this section, we will see how to declare and assign variables. You do not need to specify the data type of the variable explicitly. Let’s take an example of declaring and assigning a variable in the Python language.
The following program demonstrates declaring and assigning variables
Program
# Assigning an integer value to a variable
age = 25
print(age)
# Assigning a floating-point value to a variable
height = 5.9
print(height)
# Assigning a string value to a variable
name = "Alice"
print(name)
# Assigning a boolean value to a variable
is_student = True
print(is_student)
Output
25
5.9
Alice
True
Variable Naming Conventions
There are some rules to follow before defining a variable. Variable names must begin with a letter (a-z, A-Z) or an underscore(_). Let’s examine the rules of declaring variables in the Python language.
Start with a letter or an underscore(_): In Python language, Variable names must begin with a letter (a-z, A-Z) or an underscore(_). It cannot start with a number digit in Python language.
The following example demonstrates the start with a letter or an underscore.
_variable = 10
variable_name = “Python”
Case sensitivity: Python variables are case sensitive, which means “Age”, ‘age’ and “AGE” are three different variables in Python language.
For example
age = 25
Age = 30
No space allowed: Python variables cannot contain spaces. This variable instead of underscores(_) to separate words in variable names.
For example
first_name = "Work"
last_name = "Tom cruise"
Avoid using reserved keywords: Python developers cannot use reserved keywords, such as ‘if’, ‘else’, ‘while’, ‘for’, or ‘class’, as variable names.
Use meaningful names: In the Python language, always choose descriptive and meaningful names for your variables. This will make your code more readable and maintainable.
For example
# Bad variable name
x = 100
# Good variable name
max_speed = 100
Changing Variable Values
In the Python language, variables are dynamic, meaning they can also be changed during the program’s execution. When you assign a new value to the editing variable, the old value can be overwritten.
The following program demonstrates the Changing Variables Values in Python language.
Program
count = 10
print(count)
count = 20
print(count)
Output
10
20
Python Assigns Values to Multiple Variables
In this section, we will learn “ how to assign multiple variables in one line” and how to make your code concise and readable.
The following progarm assigns values to multiple variables:
Program
a = b = c = 5343
print(a)
print(b)
print(c)
Output
5343
5343
5343
Assigning Different Values to Multiple Variables
In this section, python allows adding different values in a single line with “,” operators.
The following program demonstrates the multiple Variables:
Program
a, b, c = 34, 5343.2, "Neeraj Kumar"
print(a)
print(b)
print(c)
Output
34
5343.2
Neeraj Kumar
How Does the + Operator Work with Variables?
The Python plus operator + this operator provides a convenient way to add value If it is a number. If those values are not numbers, then they concatenate the string.
The following program demonstrates the + operator:
Program
a = 333
b = 334
print(a+b)
a = "Kumar"
b = "Neeraj"
print(a+b)<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"> </strong>
Output
667
KumarNeeraj
Global and Local Python Variables
Local Variables: Local variables are defined and declared inside a function. We cannot use them outside the function.
The following program demonstrates the global and Local Python variable
Program
def addition():
a = 90
b = 100
c = a+b
print(c)
addition()
Output
190
Global Variables: Global variables are those variables that are defined and declared outside a function, and we need to use them inside a function in Python language.
The following program demonstrates the Global Variables
Program
def addition():
print(c)
# Global scope
a = 20
b = 30
c = a+b
addition()
Output
50
Global Keyword in Python
The global keyword in Python allows a user to modify a variable outside of the current scope. This keyword is used to create global variables from a non-global scope, for example, inside a function. This allows you to update the global variable’s value from within the function.
Rules of Global Keyword
In Python, a variable can be assigned anywhere in the program. It’s assumed to be local unless the developer explicitly declares it a global variable.
Variables that are only referenced inside a function are implicity global in Python language.
There is no need to use a global keyword in Python language outside a function.
The following program demonstrates the global keyword example in Python language.
Program
a = 10
b = 30
def addition():
global a,b
a = 30
b= 50
c = a+b
print("Addition",c)
print("Before changing:", a)
print("Before changing",b)
addition()<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"> </strong><strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"> </strong>
Output
Before changing: 10
Before changing 30
Addition 80
Types of Variables in Python
Python variables can also hold different types of data. There are some common types along with a single example for each type.
Integers(int):
Integers are whole numbers without a fractional component. The following program demonstrates the variable with an integer type.
Program
age = 3334
print(age)
Output
3334
Floating Point Numbers(float): Python variables also support real numbers. They include a decimal point to represent fractions.
The following program demonstrates the Floating Point Numbers variable.
Program
temperature = 33.43
print(temperature)
Output
33.43
Strings (str): Python variables also can store strings. The string is a character sequence.
The following program demonstrates the Strings variable in Python
Program
name = "Tom Cruise"
print(name)<strong style="font-family: Georgia, 'Times New Roman', 'Bitstream Charter', Times, serif;"> </strong>
Output
Tom Cruise
Booleans(bool): Booleans represents two values, true or false.
In this section, we will learn how to delete a variable in Python language. Python language automatically removes variables and functions from memory when they are no longer in use. The developer also can remove the variables and functions. This feature is very particularly beneficial when substantial data structures become redundant, as their deletion liberates memory for alternative applications. There is a keyword for removing the variable from the code that keyword is the ‘del’ command in Python language.
The following progarm demonstrates the ‘del’ keyword example.
Program
number=343
print(number)
del number
print(number)
Output
ERROR!
343
Traceback (most recent call last):
File "<main.py>", line 4, in <module>
NameError: name 'number' is not defined
The above program del keyword successfully deletes the number variable.
Conclusion
In this article, we learned about variable fundamentals in the Python programming language. Variables store data values and are defined using the assignment operator (‘=’). They can have descriptive names following specific rules and can change types dynamically. Variables can store common data types such as integers, floats, strings, lists, tuples, and dictionaries. We also learned about the variable scopes in this article. Understanding variables are essential skill for a Python developer.
FAQs
How to define a variable in Python language?
In Python language, we can define a variable by assigning some value to the variable name. Variable names must start with a letter (a-z, A-Z) or an underscore (_) and can be followed by letters, underscores, or digits (0-9). Python is dynamically typed. Meaning we don’t need to declare the variable type explicitly.
Can I change the type of a Python variable?
Yes, Python is a dynamically typed programming language, meaning you can change the type of a variable by assigning a new value of a different type.
What is the scope of a variable?
The scope of a variable refers to the region of the code where the variable can be accessed. Local variables are accessible only within the function they are defined in, while global variables are accessible throughout the entire program.
Can a variable name be a keyword in Python language?
Variable names cannot be keywords. Keywords are reserved words in Python that have special meanings and cannot be used as variables names, for example, ‘if’, ‘else’ and ‘while’ keywords.
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.