PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python Variables

Python Variables

Updated on: August 31, 2021 | 14 Comments

A variable is a reserved memory area (memory address) to store value. For example, we want to store an employee’s salary. In such a case, we can create a variable and store salary using it. Using that variable name, you can read or modify the salary amount.

In other words, a variable is a value that varies according to the condition or input pass to the program. Everything in Python is treated as an object so every variable is nothing but an object in Python.

A variable can be either mutable or immutable. If the variable’s value can change, the object is called mutable, while if the value cannot change, the object is called immutable. We will learn the difference between mutable and immutable types in the later section of this article.

Also, Solve:

  • Python variables and data type Quiz
  • Basic Python exercise for beginners

Table of contents

  • Creating a variable
  • Changing the value of a variable
  • Create Number, String, List variables
    • Number
      • Integer variable
      • Float variable
      • Complex type
    • String variable
    • List type variable
  • Get the data type of variable
  • Delete a variable
  • Variable’s case-sensitive
  • Constant
    • Assigning a value to a constant in Python
  • Rules and naming convention for variables and constants
  • Multiple assignments
    • Assigning a single value to multiple variables
    • Assigning multiple values to multiple variables
  • Variable scope
    • Local variable
    • Global variable
  • Object/Variable identity and references
    • Object Reference
  • Unpack a collection into a variable

Creating a variable

Python programming language is dynamically typed, so there is no need to declare a variable before using it or declare the data type of variable like in other programming languages. The declaration happens automatically when we assign a value to the variable.

Creating a variable and assigning a value

We can assign a value to the variable at that time variable is created. We can use the assignment operator = to assign a value to a variable.

The operand, which is on the left side of the assignment operator, is a variable name. And the operand, which is the right side of the assignment operator, is the variable’s value.

variable_name = variable_value

Example

name = "John"  # string assignment
age = 25  # integer assignment
salary = 25800.60  # float assignment

print(name)  # John
print(age)  # 25
print(salary)  # 25800.6

In the above example, “John”, 25, 25800.60 are values that are assigned to name, age, and salary respectively.

Changing the value of a variable

Many programming languages are statically typed languages where the variable is initially declared with a specific type, and during its lifetime, it must always have that type.

But in Python, variables are dynamically typed and not subject to the data type restriction. A variable may be assigned to a value of one type, and then later, we can also re-assigned a value of a different type. Let’s see the example.

Example

var = 10
print(var)  # 10
# print its type
print(type(var))  # <class 'int'>

# assign different integer value to var
var = 55
print(var)  # 55

# change var to string
var = "Now I'm a string"
print(var)  # Now I'm a string
# print its type
print(type(var))  # <class 'str'>

# change var to float
var = 35.69
print(var)  # 35.69
# print its type
print(type(var))  # <class 'float'>

Create Number, String, List variables

We can create different types of variables as per our requirements. Let’s see each one by one.

Number

A number is a data type to store numeric values. The object for the number will be created when we assign a value to the variable. In Python3, we can use the following three data types to store numeric values.

  1. Int
  2. float
  3. complex

Integer variable

The int is a data type that returns integer type values (signed integers); they are also called ints or integers. The integer value can be positive or negative without a decimal point.

Example

# create integer variable
age = 28
print(age)  # 28
print(type(age))  # <class 'int'>

Note: We used the built-in Python method type() to check the variable type.

Float variable

Floats are the values with the decimal point dividing the integer and the fractional parts of the number.  Use float data type to store decimal values.

Example

# create float variable
salary = 10800.55
print(salary)  # 10800.55
print(type(salary))  # <class 'float'>

In the above example, the variable salary assigned to value 10800.55, which is a float value.

Complex type

The complex is the numbers that come with the real and imaginary part. A complex number is in the form of a+bj, where a and b contain integers or floating-point values.

Example

a = 3 + 5j
print(a)  # (3+5j)
print(type(a))  # <class 'complex'>

String variable

In Python, a string is a set of characters represented in quotation marks. Python allows us to define a string in either pair of single or double quotation marks. For example, to store a person’s name we can use a string type.

To retrieve a piece of string from a given string, we can use to slice operator [] or [:]. Slicing provides us the subset of a string with an index starting from index 0 to index end-1.

To concatenate the string, we can use the addition(+) operator.

Example

# create a variable of type string
str = 'PYnative'
# prints complete string
print(str)  # PYnative

# prints first character of the string
print(str[0])  # P

# prints characters starting from 2nd to 5th
print(str[2:5])  # nat

# length of string
print(len(str))  # 8

# concatenate string
print(str + "TEST")  # PYnativeTEST

List type variable

If we want to represent a group of elements (or value) as a single entity, we should go for the list variable type. For example, we can use them to store student names. In the list, the insertion order of elements is preserved. That means, in which order elements are inserted in the list, the order will be intact.

Read: Complete Guide on Python lists

The list can be accessed in two ways, either positive or negative index.  The list has the following characteristics:

  1. In the list insertion order of elements is preserved.
  2. Heterogeneous (all types of data types int, float, string) elements are allowed.
  3. Duplicates elements are permitted.
  4. The list is mutable(can change).
  5. Growable in nature means based on our requirement, we can increase or decrease the list’s size.
  6. List elements should be enclosed within square brackets [].

Example

# create list
my_list = ['Jessa', 10, 20, 'Kelly', 50, 10.5]
# print entire list
print(my_list)  # ['Jessa', 10, 20, 'Kelly', 50, 10.5]

# Accessing 1st element of a list
print(my_list[0])  # 'Jessa'

# Accessing  last element of a
print(my_list[-1])  # 10.5

# access chunks of list data
print(my_list[1:3])  # [10, 20]

# Modifying first element of a list
my_list[0] = 'Emma'
print(my_list[0])  # 'Emma'

# add one more elements to list
my_list.append(100)
print(my_list)  # ['Emma', 10, 20, 'Kelly', 50, 10.5, 100]

Get the data type of variable

No matter what is stored in a variable (object), a variable can be any type like int, float, str, list, tuple, dict, etc. There is a built-in function called type() to get the data type of any variable.

The type() function has a simple and straightforward syntax.

Syntax of type() :

type(<variable_name>)

Example

a = 100
print(type(a))  # class 'int'

b = 100.568
print(type(b))  # class 'float'

str1 = "PYnative"
print(type(str1))  # class 'str'

my_list = [10, 20, 20.5, 100]
print(type(my_list))  # class 'list'

my_set = {'Emma', 'Jessa', 'Kelly'}
print(type(my_set))  # class 'set'

my_tuple = (5, 10, 15, 20, 25)
print(type(my_tuple))  # class 'tuple'

my_dict = {1: 'William', 2: 'John'}
print(type(my_dict))  # class 'dict'

If we want to get the name of the datatype only as output, then we can use the__name__ attribute along with the type() function. See the following example where __name__ attribute is used.

Example

my_list =[10,20,20.5,'Python',100]
# It will print only datatype of variable
print(type(my_list).__name__) # list

Delete a variable

Use the del keyword to delete the variable. Once we delete the variable, it will not be longer accessible and eligible for the garbage collector.

Example

var1 = 100
print(var1) # 100

Now, let’s delete var1 and try to access it again.

Example

var1 = 100
del var1
print(var1)

Output:

NameError: name 'var1' is not defined

Variable’s case-sensitive

Python is a case-sensitive language. If we define a variable with names a = 100 and A =200 then, Python differentiates between a and A. These variables are treated as two different variables (or objects).

Example

a = 100
A = 200

# value of a
print(a)  # 100
# Value of A
print(A)  # 200

a = a + A
print(a)  # 300

Constant

Constant is a variable or value that does not change, which means it remains the same and cannot be modified. But in the case of Python, the constant concept is not applicable. By convention, we can use only uppercase characters to define the constant variable if we don’t want to change it.

 Example

MAX_VALUE = 500

It is just convention, but we can change the value of MAX_VALUE variable.

Assigning a value to a constant in Python

As we see earlier, in the case of Python, the constant concept is not applicable. But if we still want to implement it, we can do it using the following way.

The declaration and assignment of constant in Python done with the module. Module means Python file (.py) which contains variables, functions, and packages.

So let’s create two modules, constant.py and main.py, respectively.

  • In the constant.py file, we will declare two constant variables,  PI and TOTAL_AREA.
  • import constant module In main.py file.

To create a constant module write the below code in the constant.py file.

PI = 3.14
TOTAL_AREA = 205 

Constants are declared with uppercase later variables and separating the words with an underscore.

Create a main.py and write the below code in it.

Example

import constant

print(constant.PI)
print(constant.TOTAL_AREA)

Output

3.14
205

Note: Constant concept is not available in Python. By convention, we define constants in an uppercase letter to differentiate from variables. But it does not prevent reassignment, which means we can change the value of a constant variable.

Rules and naming convention for variables and constants

A name in a Python program is called an identifier. An identifier can be a variable name, class name, function name, and module name.

There are some rules to define variables in Python.

In Python, there are some conventions and rules to define variables and constants that should follow.

Rule 1: The name of the variable and constant should have a combination of letters, digits, and underscore symbols.

  • Alphabet/letters i.e., lowercase (a to z) or uppercase (A to Z)
  • Digits(0 to 9)
  • Underscore symbol (_)

Example 

total_addition
TOTAL_ADDITION
totalAddition
Totaladdition

Rule 2: The variable name and constant name should make sense.

Note: we should always create a meaningful variable name so it will be easy to understand. That is, it should be meaningful.

Example

x = "Jessa"  
student_name = "Jessa"

It above example variable x does not make more sense, but student_name is a meaningful variable.

Rule 3: Don’t’ use special symbols in a variable name

For declaring variable and constant, we cannot use special symbols like $, #, @, %, !~, etc. If we try to declare names with a special symbol, Python generates an error

Example

ca$h = 1000

Output

ca$h = 11
      ^
SyntaxError: invalid syntax

Rule 4:  Variable and constant should not start with digit letters.

You will receive an error if you start a variable name with a digit. Let’s verify this using a simple example.

1studnet = "Jessa"
print(1studnet)

Here Python will generate a syntax error at 1studnet. instead of this, you can declare a variable like studnet_1 = "Jessa"

Rule 5: Identifiers are case sensitive.

total = 120
Total = 130
TOTAL = 150
print(total)
print(Total)
print(TOTAL)

Output

120
130
150

Here, Python makes a difference between these variables that is uppercase and lowercase, so that it will create three different variables total, Total, TOTAL.

Rule 6: To declare constant should use capital letters.

MIN_VALUE = 100
MAX_VALUE = 1000

Rule 6: Use an underscore symbol for separating the words in a variable name

If we want to declare variable and constant names having two words, use an underscore symbol for separating the words.

current_temperature = 24

Multiple assignments

In Python, there is no restriction to declare a variable before using it in the program. Python allows us to create a variable as and when required.

We can do multiple assignments in two ways, either by assigning a single value to multiple variables or assigning multiple values to multiple variables.

Assigning a single value to multiple variables

we can assign a single value to multiple variables simultaneously using the assignment operator =.

Now, let’s create an example to assign the single value 10 to all three variables a, b, and c.

Example

a = b = c = 10
print(a) # 10
print(b) # 10
print(c) # 10

Assigning multiple values to multiple variables

Example:

roll_no, marks, name = 10, 70, "Jessa"
print(roll_no, marks, name) # 10 20 Jessa

In the above example, two integer values 10 and 70 are assigned to variables roll_no and marks, respectively, and string literal, “Jessa,” is assigned to the variable name.

Variable scope

Scope: The scope of a variable refers to the places where we can access a variable.

Depending on the scope, the variable can categorize into two types local variable and the global variable.

Local variable

A local variable is a variable that is accessible inside a block of code only where it is declared. That means, If we declare a variable inside a method, the scope of the local variable is limited to the method only. So it is not accessible from outside of the method. If we try to access it, we will get an error.

Example

def test1():  # defining 1st function
    price = 900  # local variable
    print("Value of price in test1 function :", price)

def test2():  # defining 2nd function
    # NameError: name 'price' is not defined
    print("Value price in test2 function:", price)

# call functions
test1()
test2()

In the above example, we created a function with the name test1. Inside it, we created a local variable price. Similarly, we created another function with the name test2 and tried to access price, but we got an error "price is not defined" because its scope is limited to function test1(). This error occurs because we cannot access the local variable from outside the code block.

Global variable

A Global variable is a variable that is defined outside of the method (block of code). That is accessible anywhere in the code file.

Example

price = 900  # Global variable

def test1():  # defining 1st function
    print("price in 1st function :", price)  # 900

def test2():  # defining 2nd function
    print("price in 2nd function :", price)  # 900

# call functions
test1()
test2()

In the above example, we created a global variable price and tried to access it in test1 and test2. In return, we got the same value because the global variable is accessible in the entire file.

Note: You must declare the global variable outside function.

Object/Variable identity and references

In Python, whenever we create an object, a number is given to it and uniquely identifies it. This number is nothing but a memory address of a variable’s value. Once the object is created, the identity of that object never changes.

No two objects will have the same identifier. The Object is for eligible garbage collection when deleted. Python has a built-in function id() to get the memory address of a variable.

For example, consider a library with many books (memory addresses) and many students (objects). At the beginning(when we start The Python program), all books are available. When a new student comes to the library (a new object created), the librarian gives him a book. Every book has a unique number (identity), and that id number tells us which book is delivered to the student (object)

Example

n = 300
m = n
print(id(n)) # same memory address
print(id(m)) # same memory address 

It returns the same address location because both variables share the same value. But if we assign m to some different value, it points to a different object with a different identity.

See the following example

m = 500
n = 400
print("Memory address of m:", id(m))  # 1686681059984
print("Memory address of n:", id(n))  # 1686681059824

For m = 500, Python created an integer object with the value 500 and set m as a reference to it. Similarly, n is assigned to an integer object with the value 400 and sets n as a reference to it. Both variables have different identities.

Object Reference

In Python, when we assign a value to a variable, we create an object and reference it.

For example, a=10, here, an object with the value  10 is created in memory, and reference a now points to the memory address where the object is stored.

Suppose we created a=10, b=10, and  c=10, the value of the three variables is the same. Instead of creating three objects, Python creates only one object as 10 with references such as a,b,c.

We can access the memory addresses of these variables using the id() method. a, b refers to the same address in memory, and c, d, e refers to the same address. See the following example for more details.

Example

a = 10
b = 10
print(id(a))
print(id(b))

c = 20
d = 20
e = 20
print(id(c))
print(id(d))
print(id(e))

Output

140722211837248
140722211837248
140722211837568
140722211837568
140722211837568

Here, an object in memory initialized with the value 10 and reference added to it, the reference count increments by ‘1’.

When Python executes the next statement that is b=10, since it is the same value 10, a new object will not be created because the same object in memory with value 10 available, so it has created another reference, b. Now, the reference count for value 10 is ‘2’.

Again for c=20, a new object is created with reference ‘c’ since it has a unique value (20). Similarly, for d, and e new objects will not be created because the object ’20’ already available. Now, only the reference count will be incremented.

We can check the reference counts of every object by using the getrefcount function of a  sys module. This function takes the object as an input and returns the number of references.

We can pass variable, name, value, function, class as an input to getrefcount() and in return, it will give a reference count for a given object.

import sys
print(sys.getrefcount(a))
print(sys.getrefcount(c))

See the following image for more details.

Python object id references
Python object id references

In the above picture, a, b pointing to the same memory address location (i.e., 140722211837248), and c, d, e pointing to the same memory address (i.e., 140722211837568 ). So reference count will be 2 and 3 respectively.

Unpack a collection into a variable

Packing

  • In Python, we can create a tuple (or list) by packing a group of variables.
  • Packing can be used when we want to collect multiple values in a single variable. Generally, this operation is referred to as tuple packing.

Example

a = 10
b = 20
c = 20
d = 40
tuple1 = a, b, c, d # Packing tuple
print(t) # (10, 20, 20, 40)

Here a, b, c, d are packed in the tuple tuple1.

Tuple unpacking is the reverse operation of tuple packing. We can unpack tuple and assign tuple values to different variables.

Example

tuple1 = (10, 20, 30, 40)
a, b, c, d = tuple1
print(a, b, c, d)  # 10 20 30 40

Note: When we are performing unpacking, the number of variables and the number of values should be the same. That is, the number of variables on the left side of the tuple must exactly match a number of values on the right side of the tuple. Otherwise, we will get a ValueError.

Example

a, b = 1, 2, 3
print(a,b)

Output

a, b = 1, 2, 3
ValueError: too many values to unpack (expected 2)

Also, See:

  • Class Variables
  • Instance variables

Filed Under: Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python Basics
TweetF  sharein  shareP  Pin

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python Object-Oriented Programming
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com