The Wayback Machine - https://web.archive.org/web/20240922224113/https://www.geeksforgeeks.org/python-variables/
Open In App

Python Variables

Last Updated : 09 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Python Variable is containers that store values. Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. A Python variable is a name given to a memory location. It is the basic unit of storage in a program. In this article, we will see how to define a variable in Python.

Example of Variable in Python

An Example of a Variable in Python is a representational name that serves as a pointer to an object. Once an object is assigned to a variable, it can be referred to by that name. In layman’s terms, we can say that Variable in Python is containers that store values.

Here we have stored “Geeksforgeeks”  in a variable var, and when we call its name the stored information will get printed.

Python
Var = "Geeksforgeeks"
print(Var)

Output:

Geeksforgeeks

Notes:

  • The value stored in a variable can be changed during program execution.
  • A Variables in Python is only a name given to a memory location, all the operations done on the variable effects that memory location.

Rules for Python variables

  • A Python variable name must start with a letter or the underscore character.
  • A Python variable name cannot start with a number.
  • A Python variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).
  • Variable in Python names are case-sensitive (name, Name, and NAME are three different variables).
  • The reserved words(keywords) in Python cannot be used to name the variable in Python.

Example 

Python
# valid variable name
geeks = 1
Geeks = 2
Ge_e_ks = 5
_geeks = 6
geeks_ = 7
_GEEKS_ = 8

print(geeks, Geeks, Ge_e_ks)
print(_geeks, geeks_, _GEEKS_)

Output:

1 2 5
6 7 8

Variables Assignment in Python

Here, we will define a variable in python. Here, clearly we have assigned a number, a floating point number, and a string to a variable such as age, salary, and name.

Python
# An integer assignment
age = 45

# A floating point
salary = 1456.8

# A string
name = "John"

print(age)
print(salary)
print(name)

Output:

45
1456.8
John

Declaration and Initialization of Variables

Let’s see how to declare a variable and how to define a variable and print the variable.

Python
# declaring the var
Number = 100

# display
print( Number)

Output:

100

Redeclaring variables in Python

We can re-declare the Python variable once we have declared the variable and define variable in python already.

Python
# declaring the var
Number = 100

# display
print("Before declare: ", Number)

# re-declare the var
Number = 120.3
  
print("After re-declare:", Number)

Output:

Before declare:  100
After re-declare: 120.3

Python Assign Values to Multiple Variables 

Also, Python allows assigning a single value to several variables simultaneously with “=” operators. 
For example: 

Python
a = b = c = 10

print(a)
print(b)
print(c)

Output:

10
10
10

Assigning different values to multiple variables

Python allows adding different values in a single line with “,” operators.

Python
a, b, c = 1, 20.2, "GeeksforGeeks"

print(a)
print(b)
print(c)

Output:

1
20.2
GeeksforGeeks

Can We Use the Same Name for Different Types?

If we use the same name, the variable starts referring to a new value and type.

Python
a = 10
a = "GeeksforGeeks"

print(a)

Output:

GeeksforGeeks

How does + operator work with variables? 

The Python plus operator + provides a convenient way to add a value if it is a number and concatenate if it is a string. If a variable is already created it assigns the new value back to the same variable.

Python
a = 10
b = 20
print(a+b)

a = "Geeksfor"
b = "Geeks"
print(a+b)

Output
30
GeeksforGeeks

Can we use + for different Datatypes also? 

No use for different types would produce an error.

Python
a = 10
b = "Geeks"
print(a+b)

Output : 

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Global and Local Python Variables

Local variables in Python are the ones that are defined and declared inside a function. We can not call this variable outside the function.

Python
# This function uses local variable s
def f():
    s = "Welcome geeks"
    print(s)


f()

Output:

Welcome geeks

Global variables in Python are the ones that are defined and declared outside a function, and we need to use them inside a function.

Python
# This function has a variable with
# name same as s
def f():
    print(s)

# Global scope
s = "I love Geeksforgeeks"
f()

Output:

I love Geeksforgeeks

Global keyword in Python

Python global is a keyword that allows a user to modify a variable outside of the current scope. It is used to create global variables from a non-global scope i.e inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing.

Rules of global keyword

  • If a variable is assigned a value anywhere within the function’s body, it’s assumed to be local unless explicitly declared as global.
  • Variables that are only referenced inside a function are implicitly global.
  • We use a global in Python to use a global variable inside a function.
  • There is no need to use a global keyword in Python outside a function.

Example:

Python program to modify a global value inside a function.

Python
x = 15

def change():

    # using a global keyword
    global x

    # increment value of a by 5
    x = x + 5
    print("Value of x inside a function :", x)


change()
print("Value of x outside a function :", x)

Output:

Value of x inside a function : 20
Value of x outside a function : 20

Variable Types in Python

Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, data types are actually classes and variables are instances (object) of these classes.

Built-in Python Data types are:

Example:

In this example, we have shown different examples of Built-in data types in Python.

Python
# numberic
var = 123
print("Numeric data : ", var)

# Sequence Type
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Boolean
print(type(True))
print(type(False))

# Creating a Set with
# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)

Output:

Numeric data :  123
String with the use of Single Quotes:
Welcome to the Geeks World
<class 'bool'>
<class 'bool'>
Set with the use of String:
{'r', 'G', 'e', 'k', 'o', 's', 'F'}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Object Reference in Python

Let us assign a variable x to value 5.

x = 5
Object References

Another variable is y to the variable x.

y = x
Object References in Python

When Python looks at the first statement, what it does is that, first, it creates an object to represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference to this new object 5. The second line causes Python to create the variable y, and it is not assigned with x, rather it is made to reference that object that x does. The net effect is that the variables x and y wind up referencing the same object. This situation, with multiple names referencing the same object, is called a Shared Reference in Python.
Now, if we write:

x = 'Geeks'

This statement makes a new object to represent ‘Geeks’ and makes x reference this new object.

Python Variable

Now if we assign the new value in Y, then the previous object refers to the garbage values.

y = "Computer"
Object References in Python

Creating objects (or variables of a class type)

Please refer to Class, Object, and Members for more details. 

Python
class CSStudent:
    # Class Variable
    stream = 'cse'
    # The init method or constructor
    def __init__(self, roll):
        # Instance Variable
        self.roll = roll

# Objects of CSStudent class
a = CSStudent(101)
b = CSStudent(102)

print(a.stream)  # prints "cse"
print(b.stream)  # prints "cse"
print(a.roll)    # prints 101

# Class variables can be accessed using class
# name also
print(CSStudent.stream)  # prints "cse"

Output
cse
cse
101
cse

Python Variables – FAQs

What Are Variables in Python?

Variables in Python are used to store data values. They act as containers for storing data, which can be used and manipulated throughout a program. In Python, variables do not need explicit declaration to reserve memory space; the declaration happens automatically when you assign a value to a variable.

How to Declare Variables in Python?

In Python, variables are declared by assigning a value to them using the assignment operator =. You do not need to specify the type of variable as Python is dynamically typed.

Example:

# Declaring variables
name = "Alice"
age = 25
is_student = True

In this example, name is a string, age is an integer, and is_student is a boolean.

What Are Global and Local Variables in Python?

Global Variables: Global variables are variables that are declared outside of any function. They can be accessed and modified by any function within the same module.

Example:

global_var = "I am global"

def print_global():
print(global_var)

print_global() # Output: I am global

Local Variables: Local variables are variables that are declared within a function. They can only be accessed within that function and are not available outside of it.

Example:

def print_local():
local_var = "I am local"
print(local_var)

print_local() # Output: I am local
# print(local_var) # This would raise an error because local_var is not accessible outside the function.

Can Variable Types Change in Python?

Yes, variable types can change in Python because it is a dynamically typed language. This means that the type of a variable is interpreted at runtime and you can assign different types of values to the same variable.

Example:

var = 10    # var is an integer
var = "Hello" # Now var is a string
var = [1, 2, 3] # Now var is a list

How to Use Type Annotations for Variables in Python?

Type annotations in Python provide a way to specify the expected type of a variable. They do not enforce type checking at runtime but can be used by static type checkers, IDEs, and linters to help catch type-related errors.

Example:

# Using type annotations
name: str = "Alice"
age: int = 25
is_student: bool = True

def greeting(name: str) -> str:
return f"Hello, {name}"

# Static type checkers can use these annotations to detect type errors

In this example, the variables name, age, and is_student are annotated with their expected types. The function greeting also has type annotations for its parameter and return type.



Similar Reads

Python | Set 2 (Variables, Expressions, Conditions and Functions)
Introduction to Python has been dealt with in this article. Now, let us begin with learning python. Running your First Code in Python Python programs are not compiled, rather they are interpreted. Now, let us move to writing python code and running it. Please make sure that python is installed on the system you are working on. If it is not installe
3 min read
Python | Difference between Pandas.copy() and copying through variables
Pandas .copy() method is used to create a copy of a Pandas object. Variables are also used to generate copy of an object but variables are just pointer to an object and any change in new data will also change the previous data. The following examples will show the difference between copying through variables and Pandas.copy() method. Example #1: Co
2 min read
Inserting variables to database table using Python
In this article, we will see how one can insert the user data using variables. Here, we are using the sqlite module to work on a database but before that, we need to import that package. import sqlite3 To see the operation on a database level just download the SQLite browser database.Note: For the demonstration, we have used certain values but you
3 min read
How are variables stored in Python - Stack or Heap?
Memory allocation can be defined as allocating a block of space in the computer memory to a program. In Python memory allocation and deallocation method is automatic as the Python developers created a garbage collector for Python so that the user does not have to do manual garbage collection. Garbage Collection Garbage collection is a process in wh
3 min read
Python Scope of Variables
In Python, variables are the containers for storing data values. Unlike other languages like C/C++/JAVA, Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. Python Scope variable The location where we can find a variable and al
5 min read
Tracing Tkinter variables in Python
There is no inbuilt way to track variables in Python. But tkinter supports creating variable wrappers that can be used to do so by attaching an 'observer' callback to the variable. The tkinter.Variable class has constructors like BooleanVar, DoubleVar, IntVarand StringVar for boolean, double-precision floating-point values, integer and strings resp
3 min read
How to Create Dummy Variables in Python with Pandas?
A dataset may contain various type of values, sometimes it consists of categorical values. So, in-order to use those categorical value for programming efficiently we create dummy variables. A dummy variable is a binary variable that indicates whether a separate categorical variable takes on a specific value. Explanation: As you can see three dummy
2 min read
Context Variables in Python
Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work with context variables in python. Note: This is supp
4 min read
Environment Variables in Python
In Python, its behavior is highly influenced by the setup of the environment variables. There is a fixed number of environment variables that Python recognizes and these generally are processed before the command line switches. Whenever a conflict arises between the environmental variable and the command line switches, the environment variable gets
4 min read
Assigning multiple variables in one line in Python
A variable is a segment of memory with a unique name used to hold data that will later be processed. Although each programming language has a different mechanism for declaring variables, the name and the data that will be assigned to each variable are always the same. They are capable of storing values of data types. The assignment operator(=) assi
2 min read
Viewing all defined variables in Python
In this article, we are going to discuss how to view all defined variables in Python. Viewing all defined variables plays a major role while debugging the code. Method 1: Using dir() function dir() is a built-in function to store all the variables inside a program along with the built-in variable functions and methods. It creates a list of all decl
5 min read
How to check multiple variables against a value in Python?
Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python: Method #1: Using or operator This is pretty simple and straightforward. The following code snippets illustrate this method. Example 1: C/C++ Code # assigning variables a = 100 b = 0
2 min read
How to use Pickle to save and load Variables in Python?
Serialization is a technique used to save the state of an object from any process. We can later use this state by deserialization, to continue the process. Pickle is a python module that makes it easy to serialize or save variables and load them when needed. Unlike JSON serialization, Pickle converts the object into a binary string. JSON is text sp
2 min read
How to import variables from another file in Python?
When the lines of code increase, it is cumbersome to search for the required block of code. It is a good practice to differentiate the lines of code according to their working. It can be done by having separate files for different working codes. As we know, various libraries in Python provide various methods and variables that we access using simpl
2 min read
How to handle missing values of categorical variables in Python?
Machine Learning is the field of study that gives computers the capability to learn without being explicitly programmed. Often we come across datasets in which some values are missing from the columns. This causes problems when we apply a machine learning model to the dataset. This increases the chances of error when we are training the machine lea
4 min read
How to plot a histogram with various variables in Matplotlib in Python?
In this article, we are going to see how to plot a histogram with various variables in Matplotlib using Python. A histogram is a visual representation of data presented in the form of groupings. It is a precise approach for displaying numerical data distribution graphically. It's a type of bar plot in which the X-axis shows bin ranges and the Y-axi
3 min read
Python - Scipy curve_fit with multiple independent variables
Curve fitting examines the relationship between one or more predictors (independent variables) and a response variable (dependent variable), with the goal of defining a "best fit" model of the relationship. It is the process of constructing a mathematical function, that has the best fit to a series of data points possibly subject to constraints. Cu
3 min read
Python - Pearson Correlation Test Between Two Variables
What is correlation test? The strength of the association between two variables is known as correlation test. For instance, if we are interested to know whether there is a relationship between the heights of fathers and sons, a correlation coefficient can be calculated to answer this question.For know more about correlation please refer this.Method
3 min read
Private Variables in Python
Prerequisite: Underscore in PythonIn Python, there is no existence of “Private” instance variables that cannot be accessed except inside an object. However, a convention is being followed by most Python code and coders i.e., a name prefixed with an underscore, For e.g. _geek should be treated as a non-public part of the API or any Python code, whet
3 min read
Global and Local Variables in Python
Python Global variables are those which are not defined inside any function and have a global scope whereas Python local variables are those which are defined inside a function and their scope is limited to that function only. In other words, we can say that local variables are accessible only inside the function in which it was initialized whereas
7 min read
Read Environment Variables with Python dotenv
Environment variables play a crucial role in the configuration and operation of software applications. They provide a mechanism to store configuration settings that can be used by applications to function properly. This separation of configuration from code allows for more secure and flexible software development practices. Introduction to python-d
4 min read
Class or Static Variables in Python
All objects share class or static variables. An instance or non-static variables are different for different objects (every object has a copy). For example, let a Computer Science Student be represented by a class CSStudent. The class may have a static variable whose value is "cse" for all objects. And class may also have non-static members like na
7 min read
XOR of Two Variables in Python
The XOR or exclusive is a Boolean logic operation widely used in cryptography and generating parity bits for error checking and fault tolerance. The operation takes in two inputs and produces a single output. The operation is bitwise traditionally but could be performed logically as well. This article will teach you how to get the logical XOR of tw
7 min read
Pass JavaScript Variables to Python in Flask
In this tutorial, we'll look at using the Flask framework to leverage JavaScript variables in Python. In this section, we'll talk about the many approaches and strategies used to combine the two languages, which is an essential step for many online applications. Everything from the fundamentals to more complex subjects, such as how to handle enormo
7 min read
Kotlin Variables
In Kotlin, every variable should be declared before it's used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location. In case of local variables, the type of variable can be inferred from the initialized value.
2 min read
variables - Django Templates
A Django template is a text document or a Python string marked-up using the Django template language. Django being a powerful Batteries included framework provides convenience to rendering data in a template. Django templates not only allow passing data from view to template, but also provides some limited features of a programming such as variable
2 min read
Grouping Categorical Variables in Pandas Dataframe
Firstly, we have to understand what are Categorical variables in pandas. Categorical are the datatype available in pandas library of python. A categorical variable takes only a fixed category (usually fixed number) of values. Some examples of Categorical variables are gender, blood group, language etc. One main contrast with these variables are tha
2 min read
How to use Variables in Python3?
Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store integers, strings, decimals, complex in these vari
3 min read
Visualizing Relationship between variables with scatter plots in Seaborn
To understand how variables in a dataset are related to one another and how that relationship is dependent on other variables, we perform statistical analysis. This Statistical analysis helps to visualize the trends and identify various patterns in the dataset. One of the functions which can be used to get the relationship between two variables in
2 min read
Variables and autograd in Pytorch
PyTorch is a python library developed by Facebook to run and train the machine and deep learning algorithms. In a neural network, we have to perform backpropagation which involves optimizing the parameter to minimize the error in its prediction. For this PyTorch offers torch.autograd that does automatic differentiation by collecting all gradients.
3 min read
Practice Tags :