PYnative

Practice Coding

  • Python â–¼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Coding Exercises â–¼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • MCQsâ–¼
    • Python MCQ Quizzes
    • Java MCQ Quizzes
    • C++ MCQ Quizzes
  • Compilersâ–¼
    • Online Python Compiler
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Python Variables

Python Variables

Updated on: November 30, 2026 | 22 Comments

A variable is a name that refers to a value stored in memory. For example, if you want to store an employee’s salary, you can create a variable called salary and assign the amount to it. Later, you can use that variable name to read or change the salary.

Everything in Python is an object, so a variable is really a label (reference) attached to an object. The value it refers to can change as your program runs, for example, based on a condition or on user input. That’s why it’s called a variable.

The object a variable refers to can be either mutable or immutable. A mutable object (such as a list) can be changed in place, while an immutable object (such as an integer or a string) cannot. You’ll learn the difference later in 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, and list variables
    • Number
      • Integer variable
      • Float variable
      • Complex type
    • String variable
    • List type variable
    • Boolean and None
  • Get the data type of a variable
  • Convert a variable to another type
  • Print variables with f-strings
  • Delete a variable
  • Variables are 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
  • Mutable and immutable objects
  • Unpack a collection into variables
  • Summary

Creating a variable

Python is dynamically typed, so you don’t need to declare a variable or its data type before using it, as you do in languages like C or Java. A variable is created automatically the first time you assign a value to it.

Creating a variable and assigning a value

Use the assignment operator = to assign a value to a variable. The name on the left side of = is the variable name, and the expression on the right side is the value.

variable_name = variable_valueCode language: Python (python)

Example

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

print(name)  # John
print(age)  # 25
print(salary)  # 25800.6Code language: Python (python)

In this example, “John”, 25, and 25800.60 are assigned to the variables name, age, and salary, respectively.

Type hints (optional): You can add a type annotation to show what kind of value a variable should hold, for example, price: float = 9.99. Python doesn’t enforce it, but editors and tools use it to catch mistakes.

Changing the value of a variable

Many programming languages are statically typed: a variable is declared with a specific type and must keep that type for its whole lifetime.

Python variables are dynamically typed and are not tied to a data type. You can assign a value of one type to a variable and later reassign it to a value of a different type.

Example

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

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

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

# change var to a float
var = 35.69
print(var)  # 35.69
print(type(var))  # <class 'float'>Code language: Python (python)

Create number, string, and list variables

You can create variables of different types depending on what you need to store. Let’s look at the most common ones.

Number

Numbers are data types that store numeric values. Python creates the number object when you assign the value to a variable. Python 3 has three numeric types:

  1. int
  2. float
  3. complex

Integer variable

The int type stores whole numbers, also called integers. They can be positive or negative and have no decimal point. Python integers have no size limit.

Example

# create integer variable
age = 28
print(age)  # 28
print(type(age))  # <class 'int'>Code language: Python (python)

Note: We used the built-in type() function to check the variable’s type.

Float variable

Floats are numbers with a decimal point separating the whole and fractional parts. Use the float type to store decimal values.

Example

# create float variable
salary = 10800.55
print(salary)  # 10800.55
print(type(salary))  # <class 'float'>Code language: Python (python)

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

Complex type

A complex number has a real part and an imaginary part. It is written in the form a + bj, where a and b are integers or floats and j represents the imaginary unit.

Example

a = 3 + 5j
print(a)  # (3+5j)
print(type(a))  # <class 'complex'>Code language: Python (python)

String variable

In Python, a string is a sequence of characters enclosed in quotation marks. You can use either single or double quotes. For example, use a string to store a person’s name.

To get a single character, use indexing with []. To get a part of a string, use the slice operator [start:end], which returns the characters from index start up to, but not including, index end. Indexes start at 0.

To join (concatenate) strings, use the addition (+) operator.

Example

# create a variable of type string
site_name = 'PYnative'
# print the complete string
print(site_name)  # PYnative

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

# print characters from index 2 up to index 4
print(site_name[2:5])  # nat

# length of the string
print(len(site_name))  # 8

# concatenate strings
print(site_name + "TEST")  # PYnativeTESTCode language: Python (python)

Tip: Don’t name a variable str, list, or type. Those names already belong to built-in functions, and reusing them hides the built-in.

List type variable

Use a list when you want to store a group of values as a single entity, for example, a list of student names.

Read: Complete guide on Python lists

You can access list items using a positive index (counting from the start) or a negative index (counting from the end). Lists have the following characteristics:

  1. The insertion order of items is preserved.
  2. Items can be of different types (int, float, str, and so on).
  3. Duplicate items are allowed.
  4. Lists are mutable: you can change their items.
  5. Lists can grow and shrink as needed.
  6. List items are enclosed in 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]

# access the first item of the list
print(my_list[0])  # Jessa

# access the last item of the list
print(my_list[-1])  # 10.5

# access a slice of the list
print(my_list[1:3])  # [10, 20]

# modify the first item of the list
my_list[0] = 'Emma'
print(my_list[0])  # Emma

# add one more item to the list
my_list.append(100)
print(my_list)  # ['Emma', 10, 20, 'Kelly', 50, 10.5, 100]Code language: Python (python)

Boolean and None

A bool variable holds one of two values, True or False. It is often the result of a comparison. The special value None means “no value” and is often used as a placeholder.

is_active = True
is_adult = 20 >= 18
print(is_active, is_adult)  # True True

result = None
print(result, type(result))  # None <class 'NoneType'>Code language: Python (python)

Get the data type of a variable

A variable can refer to a value of any type, such as int, float, str, list, tuple, or dict. To find out the type of the value a variable currently holds, use the built-in type() function.

Syntax of type():

type(variable_name)Code language: Python (python)

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'>Code language: Python (python)

If you only want the name of the type, use the __name__ attribute of the result:

Example

my_list = [10, 20, 20.5, 'Python', 100]
# print only the name of the data type
print(type(my_list).__name__)  # listCode language: Python (python)

To check whether a variable is of a certain type, use isinstance(), for example, isinstance(a, int) returns True.

Convert a variable to another type

You can convert (cast) a value to another type with the built-in functions int(), float(), str(), list(), and so on. This is common when you read input from the user, because input() always returns a string.

age = "25"              # a string
print(int(age) + 5)     # 30
print(float("3.5"))     # 3.5
print(str(10) + "!")    # 10!Code language: Python (python)

Print variables with f-strings

An f-string (a string prefixed with f) lets you put variables directly inside text using curly braces. It is the easiest way to display variables in a message.

name = "Jessa"
age = 28
print(f"{name} is {age} years old")
# Output: Jessa is 28 years oldCode language: Python (python)

Delete a variable

Use the del keyword to delete a variable. After you delete it, the name is no longer accessible. If no other variable refers to the same object, Python’s garbage collector frees its memory.

Example

var1 = 100
print(var1)  # 100Code language: Python (python)

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

Example

var1 = 100
del var1
print(var1)Code language: Python (python)

Output:

NameError: name 'var1' is not defined

Variables are case-sensitive

Python is a case-sensitive language. If you define a = 100 and A = 200, Python treats a and A as two different variables.

Example

a = 100
A = 200

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

a = a + A
print(a)  # 300Code language: Python (python)

Constant

A constant is a value that should not change while the program runs. Python has no built-in way to make a variable truly constant. Instead, by convention, you write constant names in all uppercase letters to tell other programmers not to change them.

Example

MAX_VALUE = 500Code language: Python (python)

This is only a convention: Python still lets you change the value of MAX_VALUE. If you use a type checker, you can mark a name with typing.Final (for example, MAX_VALUE: Final = 500) so the checker reports any reassignment.

Assigning a value to a constant in Python

A common practice is to keep all constants together in a separate module. A module is simply a Python file (.py) that contains variables, functions, or classes.

Let’s create two modules, constant.py and main.py:

  • In constant.py, declare two constants, PI and TOTAL_AREA.
  • In main.py, import the constant module and use them.

Write the following code in the constant.py file:

PI = 3.14
TOTAL_AREA = 205Code language: Python (python)

Constant names use uppercase letters, with words separated by underscores.

Now create main.py and write the following code in it:

Example

import constant

print(constant.PI)
print(constant.TOTAL_AREA)Code language: Python (python)

Output

3.14
205

Note: Writing names in uppercase marks them as constants, but it doesn’t prevent reassignment.

Rules and naming convention for variables and constants

A name in a Python program is called an identifier. Variable names, function names, class names, and module names are all identifiers. Follow these rules and conventions when naming variables and constants.

Rule 1: A name can contain only letters, digits, and underscores:

  • Letters: lowercase (a to z) or uppercase (A to Z)
  • Digits (0 to 9)
  • Underscore (_)

Example

total_addition
TOTAL_ADDITION
totalAddition
TotaladditionCode language: Python (python)

Rule 2: A name can’t start with a digit.

1student = "Jessa"   # SyntaxError
student_1 = "Jessa"  # validCode language: Python (python)

Rule 3: Don’t use special symbols such as $, #, @, %, !, or ~ in a name. Python raises a syntax error if you do.

Example

ca$h = 1000Code language: Python (python)

Output

    ca$h = 1000
      ^
SyntaxError: invalid syntax

Rule 4: Don’t use Python keywords such as if, for, class, or True as names. They are reserved for the language itself.

Rule 5: Names are case-sensitive.

total = 120
Total = 130
TOTAL = 150
print(total)
print(Total)
print(TOTAL)Code language: Python (python)

Output

120
130
150

Python treats uppercase and lowercase letters as different, so it creates three separate variables: total, Total, and TOTAL.

Convention 1: Choose meaningful names that describe the value.

x = "Jessa"             # unclear
student_name = "Jessa"  # meaningfulCode language: Python (python)

Convention 2: Use lowercase words separated by underscores for variable names (this style is called snake_case).

current_temperature = 24Code language: Python (python)

Convention 3: Use uppercase letters with underscores for constants.

MIN_VALUE = 100
MAX_VALUE = 1000Code language: Python (python)

Multiple assignments

Python lets you assign values to several variables in a single statement. There are two ways to do this: assign a single value to multiple variables, or assign multiple values to multiple variables.

Assigning a single value to multiple variables

You can chain the assignment operator = to give several variables the same value at once. Here, all three variables a, b, and c get the value 10.

Example

a = b = c = 10
print(a)  # 10
print(b)  # 10
print(c)  # 10Code language: Python (python)

Assigning multiple values to multiple variables

Example:

roll_no, marks, name = 10, 70, "Jessa"
print(roll_no, marks, name)  # 10 70 JessaCode language: Python (python)

Here, the integers 10 and 70 are assigned to roll_no and marks, and the string “Jessa” is assigned to name.

This also gives you an easy way to swap two variables without a temporary variable:

x, y = 5, 9
x, y = y, x
print(x, y)  # 9 5Code language: Python (python)

Variable scope

The scope of a variable is the part of the program where you can access it.

Depending on their scope, variables fall into two main types: local variables and global variables.

Local variable

A local variable is created inside a function and can only be used inside that function. If you try to access it from outside the function, you get an error.

Example

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

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

# call functions
test1()
test2()Code language: Python (python)

Here, we created a local variable price inside the function test1(). In test2(), we tried to access price, but we got the error name 'price' is not defined, because its scope is limited to test1().

Global variable

A global variable is defined outside of any function, at the top level of the file. It can be read from anywhere in that file, including inside functions.

Example

price = 900  # global variable

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

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

# call functions
test1()
test2()Code language: Python (python)

Both functions print the same value because the global variable is accessible throughout the file.

Note: A function can read a global variable, but to change it inside a function, you must declare it with the global keyword. Otherwise, Python creates a new local variable instead.

count = 0

def increment():
    global count
    count += 1

increment()
increment()
print(count)  # 2Code language: Python (python)

Object/variable identity and references

Whenever Python creates an object, it gives the object a unique number called its identity. In CPython (the standard Python implementation), this number is the object’s memory address. An object’s identity never changes during its lifetime, and no two objects that exist at the same time share the same identity. The built-in id() function returns it.

Think of a library: the books are memory locations, and the students are objects. When a new student arrives (a new object is created), the librarian gives them a book with a unique number (the identity). That number tells you exactly which book belongs to which student.

Example

n = 300
m = n
print(id(n))  # same memory address
print(id(m))  # same memory address
print(n is m)  # TrueCode language: Python (python)

Both lines print the same address because m = n doesn’t copy the value. It makes m refer to the same object as n. The is operator checks whether two variables refer to the same object. If you later assign a different value to m, it refers to a different object with a different identity.

m = 500
n = 400
print("Memory address of m:", id(m))  # e.g. 1686681059984
print("Memory address of n:", id(n))  # e.g. 1686681059824Code language: Python (python)

For m = 500, Python creates an integer object with the value 500 and makes m refer to it. Similarly, n refers to an integer object with the value 400. The two variables have different identities. (The exact numbers will differ on your computer.)

Object reference

When you assign a value to a variable, Python creates (or reuses) an object and makes the variable refer to it.

For example, with a = 10, an object with the value 10 is stored in memory, and the name a points to it.

For efficiency, CPython keeps a single shared object for each small integer (from -5 to 256) and for many short strings. So if you write a = 10 and b = 10, both names refer to the same object instead of two separate ones. This is an internal optimization: don’t rely on it for larger numbers, and always compare values with == rather than is.

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))Code language: Python (python)

Output (addresses will differ on your computer)

140722211837248
140722211837248
140722211837568
140722211837568
140722211837568

a and b refer to the same object with the value 10, and c, d, and e all refer to the same object with the value 20.

Python keeps track of how many references point to each object (its reference count). When the count drops to zero, the object’s memory is freed. You can check the count with sys.getrefcount():

import sys
print(sys.getrefcount(a))
print(sys.getrefcount(c))Code language: Python (python)

The numbers you see will usually be larger than you expect, because Python itself (and the call to getrefcount()) also hold references to these shared objects.

Python object id references
Python object id references

In the image above, a and b point to the same memory location, and c, d, and e point to another shared location.

Mutable and immutable objects

  • Immutable objects can’t be changed after they are created: int, float, bool, str, tuple, and frozenset. “Changing” one actually creates a new object.
  • Mutable objects can be changed in place: list, dict, and set.

This matters when two variables refer to the same object:

# mutable: both names see the change
a = [1, 2, 3]
b = a
b.append(4)
print(a)  # [1, 2, 3, 4]

# immutable: a new object is created
s = "hi"
t = s
t = t + "!"
print(s, t)  # hi hi!Code language: Python (python)

Because b = a doesn’t copy the list, changing it through b also changes what a sees. To get an independent copy, use b = a.copy().

Unpack a collection into variables

Packing

  • You can create a tuple by packing several values into a single variable.
  • This is called tuple packing, and it is useful when you want to collect multiple values in one variable.

Example

a = 10
b = 20
c = 20
d = 40
tuple1 = a, b, c, d  # packing a tuple
print(tuple1)  # (10, 20, 20, 40)Code language: Python (python)

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

Tuple unpacking is the reverse of packing. It assigns the values of a tuple (or any sequence) to separate variables.

Example

tuple1 = (10, 20, 30, 40)
a, b, c, d = tuple1
print(a, b, c, d)  # 10 20 30 40Code language: Python (python)

Note: When unpacking, the number of variables on the left must match the number of values on the right. Otherwise, you get a ValueError.

Example

a, b = 1, 2, 3
print(a, b)Code language: Python (python)

Output

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

To collect “the rest” of the values, put an asterisk (*) before one variable name. That variable receives a list of the remaining values:

first, *rest = [1, 2, 3, 4]
print(first, rest)  # 1 [2, 3, 4]

*init, last = [1, 2, 3, 4]
print(init, last)   # [1, 2, 3] 4Code language: Python (python)

Summary

  • A variable is a name that refers to an object. It is created the first time you assign a value with =.
  • Python is dynamically typed: a variable can refer to values of different types over time. Use type() or isinstance() to check the type.
  • Convert between types with int(), float(), str(), and similar functions.
  • Names can contain letters, digits, and underscores, can’t start with a digit, can’t be keywords, and are case-sensitive. Use snake_case for variables and UPPER_CASE for constants.
  • Local variables live inside a function. Global variables live at the top level of a file, and you need the global keyword to change them inside a function.
  • Assigning one variable to another shares the same object. This matters for mutable objects such as lists.
  • Use packing and unpacking (including *rest) to work with several values at once.

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

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

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 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes
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 OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

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

About PYnative

PYnative.com is a platform built to help developers learn by doing. Solve coding exercises, take MCQs, and run code directly in built-in online compilers.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

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

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

MCQ Quizzes

  • Python MCQs
  • Java MCQs
  • C++ MCQs

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
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com