×

Python Variables

Variables are one of the most important terms we should be familiar with if we want to be good programmers. In simpler words, we use variables to store a value. We can think of variables as a name given to a container that is used to store a value, and they can be changed anytime during the execution of the program.

The syntax for creating variables in Python

Variable_name = value

Rules of Creating Variable

  • A variable name can only contain alpha-numeric characters (A-z, 0-9) and underscore ( _ ).
  • We cannot start a variable name with a number. For example, 12a is an invalid variable.
  • A variable name can start with an underscore. For example, _x is a valid variable.
  • A variable name can start with a letter. For example, age can be a variable name.
  • We can’t use keywords as variable names.

Valid Variable Names

  • first_var
  • firstvar
  • _first_var
  • firstVar
  • FIRSTVAR

Invalid Variable Names

  • 1stvar
  • first-var
  • first var

Type of Variable Names

  1. Camel Case: Except for the first word, each word starts with a capital letter in Camel Case.
    For example, myAge.
  2. Pascal Case: Each word of the variable name starts with a capital letter in Pascal Case.
    For example,  MyAge.
  3. Snake Case: Each word of the variable name is separated by an underscore in a Snake case.
    For example, my_age.

Variable Declaration

A variable can be created the moment you assign a value to it. Python doesn’t have any particular command to create a variable.

We don’t have to declare a variable in python before using it. Python is not statically typed, so we don’t have to declare the data type before using any variable. We can assign a value with the ‘=’ operator and start using it. But we can change its data type after they have been set in a code.

Let’s understand with example:

#declaring the variables
a = 9                                                         #a is of type integer
b = 10.5                                                    #b is of type float
c = “TutorialAndExample”                     #c is of type string


#displaying the variables
print(a)
print(b)
print(c)

Output:

9
10.5
TutorialAndExample

Re-declaration of Variables:

Variables can be re-declared any number of times in a program. It doesn’t affect the program but the memory location where the value is stored.

Let’s understand with an example.

#declare the variable
a =  20
# re-declare the variable a
a =  40


#display the variable
print(a)

Output:

40

Explanation:

In this code, a is first assigned a value of 20, but later, it gets re-assigned with a value of 40. Now, if we print, the value of it will be 40, not 20.

Assigning One Value to Multiple Variables:

We can assign one value to more than one variable simultaneously. For that, we use the ‘=’ operator.

Let’s understand with an example.

#assigning one value to multiple variables
a = b = c = 4
#displaying the values
print(a)
print(b)
print(c)  

Output:

4
4
4

Explanation:

In the above code, all three variables (a, b, c) are assigned the same value, which is 4. In this code, the variables are differentiated through ‘=’.

Assigning Multiple Values to Multiple variables:

Python allows assigning different values to different variables in a single line. For which we use the ‘,’ operators. In this kind of declaration, we need to ensure that the number of values is the same as the number of variables. Otherwise, it will throw an error.

For example,

#single line declaration of multiple value
 a, b, c = 1, “TutorialAndExample”, 10.5
# displaying value
print(a)
print(b)
print(c)

Outputs:

1
TutorialAndExample
10.5

Explanation:

In the above code, three variables (a,b,c) are assigned three different values. The first variable, a, is assigned a value of 1, an integer. The second variable, b, is assigned a String which is TutorialAndExample. The third variable, c, is assigned a float value which is 10.5.

Local Variables & Global Variables

Local and global variables are defined based on the position where it is declared. This is very important to understand these two terms and be able to differentiate if a variable is local or global.

Local Variable:

If a variable is declared inside the function, it is called a local variable. We cannot call local variables outside the function because they are defined and declared inside it.

Let’s understand with an example.

# This function is using local variable 
def fun ( ):
     age = 20
     print ( age )


fun ( ) 

Output:

20

Global Variable:

If a variable is declared outside the function, it is called a global variable. We use global variables inside the function, although they are defined and declared outside it.

Let’s understand with an example.

# This function is using global variable
def fun ( ):
    print (age)


age = 20
fun ( )

Output:

20

We can change a local variable to a global one using the keyword “global” in the function. We only use this keyword frequently when we want to change the value.

def fun ( ):
     global x
     x = “TutorialAndExample”
     print(x)
fun ( )
print(“Hi! Welcome to” + x)

Output:

TutorialAndExample
Hi! Welcome to TutorialAndExample

Conclusion

  • A variable is a container storing a value that can be changed anytime throughout the program.
  • A variable can be created using the syntax variable_name = value.
  • Any variable name should be descriptive. Since it will help the programmer to understand the code better. 

Related Topics

Python issubclass() Function

Python issubclass() Function The issubclass() function in Python returns a boolean value ‘True’ if the given object is a subclass of classinfo, else it returns False. Syntax issubclass(class, classinfo) Parameter class: It is a required parameter which represents a tuple...

1 minute read.

Python System Command

To execute a program in Python, we need to execute some shell commands to run our program on the computer. Python will provide some shell commands in our background to...

3 minutes read.

Self in Python

 “self" is neither a keyword nor has a special meaning in Python, but it has a place and a job to do in Object-oriented programming. When we create a class...

6 minutes read.

Magento 2 Site optimization

Magento 2 Site optimization Magento 2 is a CMS, commonly referred to as Intensive efficiency. Improving the speed and reliability of your Magento 2 app helps clients to achieve a better user experience while...

2 minutes read.

Python Syntax Error Invalid Syntax

Python is renowned for its simple and direct syntax. However, we might come across some things that Python doesn't allow if we are learning Python for the very first time or if...

14 minutes read.

XGBoost for Regression in Python

Regression problem results real values. Decision Trees and Linear Regression are regularly used regression algorithms and use some metrics involved in regression like mean squared error and root mean squared...

5 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Google Chrome API in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to declare array in python

How to declare array in python? Arrays are a great way of storing our numeric values into a variable in continuous locations. For declaring an array in C language, we used...

4 minutes read.

Python String Negative Indexing

This page contains all the information how to use “Negative indexing“ in Python with the help of using slicing. What is an Index? An index is a numeric value, which is assigned...

3 minutes read.

Defaultdict in Python

In this tutorial, we will study What is defaultdict in Python We will understand it with the aid of certain examples. Before this, we will have a look at dictionaries...

3 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Python Knapsack problem

Python Knapsack problem Before we dig down about Knapsack problems in Python, first let's have a look at what is actually a knapsack problem. What is a knapsack problem? A problem from the...

5 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

How to Convert A List into String In Python?

How to Convert A List into String In Python? List is a data structure in Python that can hold values of different data types. The values are enclosed in square brackets...

3 minutes read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Confusion Matrix Visualization Python

The confusion matrix is a two-dimensional array that compares the anticipated and actual category labels. These are the True Positive, True Negative, False Positive, and False Negative classification categories for...

4 minutes read.

How to Call a Function in Python

How To Call a Function in Python Functions are the well-defined and structured piece of code that is used to implement specific functionality. Calling a function in python is the best...

4 minutes read.

Application to get live USD/INR rate Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

4 minutes read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.