Open In App

Python Variables

Last Updated : 15 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Python3




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 

Python3




# 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.

Python3




# 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.

Python3




# 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.

Python3




# 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: 

Python3




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.

Python3




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.

Python3




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.

Python3




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.

Python3




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.

Python3




# This function uses global 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.

Python3




# 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.

Python3




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.

Python3




# 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. 

Python3




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


Frequently Asked Questions

1. How to define a variable in Python?

In Python, we can define a variable by assigning a value to a 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; it will be inferred based on the assigned value.

2. Are there naming conventions for Python variables?

Yes, Python follows the snake_case convention for variable names (e.g., my_variable). They should start with a letter or underscore, followed by letters, underscores, or numbers. Constants are usually named in ALL_CAPS.

3. Can I change the type of a Python variable?

Yes, Python is dynamically typed, meaning you can change the type of a variable by assigning a new value of a different type. For instance:

Python3




my_variable = 42  # Integer
my_variable = "Hello, Python!"  # String




Previous Article
Next Article

Similar Reads

Using Python Environment Variables with Python Dotenv
Python dotenv is a powerful tool that makes it easy to handle environment variables in Python applications from start to finish. It lets you easily load configuration settings from a special file (usually named .env) instead of hardcoding them. This makes your code more secure, easier to manage, and better organized. In this article, we'll see over
3 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
5 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
5 min read
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 | Extract key-value of dictionary in variables
Sometimes, while working with dictionaries, we can face a problem in which we may have just a singleton dictionary, i.e dictionary with just a single key-value pair, and require to get the pair in separate variables. This kind of problem can come in day-day programming. Let's discuss certain ways in which this can be done. Method #1: Using items()
5 min read
Python - Breaking Up String Variables
Prerequisite: itertools Given a String, the task is to write a Python program to break up the string and create individual elements. Input : GeeksForGeeksOutput : [ 'G', 'e', 'e', 'k', 's', 'F', 'o', 'r', 'G', 'e', 'e', 'k', 's' ] Input: ComputerOutput: [ 'C', 'o', 'm', 'p', 'u', 't', 'e', 'r'] Below are some ways to do the above task. Method #1: U
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
Python | Assign multiple variables with list values
We generally come through the task of getting certain index values and assigning variables out of them. The general approach we follow is to extract each list element by its index and then assign it to variables. This approach requires more line of code. Let's discuss certain ways to do this task in compact manner to improve readability. Method #1
4 min read
Python program to find number of local variables in a function
Given a Python program, task is to find the number of local variables present in a function. Examples: Input : a = 1 b = 2.1 str = 'GeeksForGeeks' Output : 3 We can use the co_nlocals() function which returns the number of local variables used by the function to get the desired result. Code #1: # Implementation of above approach # A function contai
1 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
Practice Tags :