0% found this document useful (0 votes)
39 views15 pages

Python Variables - GeeksforGeeks

46789

Uploaded by

ap6902557
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views15 pages

Python Variables - GeeksforGeeks

46789

Uploaded by

ap6902557
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Search...

Python Course Python Tutorial Interview Questions Python Quiz Python Glossary Python Proje

Python Variables
Last Updated : 07 Mar, 2025

In Python, variables are used to store data that can be referenced and
manipulated during program execution. A variable is essentially a name
that is assigned to a value. Unlike many other programming languages,
Python variables do not require explicit declaration of type. The type of
the variable is inferred based on the value assigned.

Variables act as placeholders for data. They allow us to store and reuse
values in our program.

Example:

# Variable 'x' stores the integer value 10


x = 5

# Variable 'name' stores the string "Samantha"


name = "Samantha"

print(x)
print(name)

Output

5
Samantha

In this article, we’ll explore the concept of variables in Python, including


their syntax, characteristics and common operations.

Table of Content
Rules for Naming Variables
Assigning Values to Variables
Multiple Assignments
Type Casting a Variable
https://www.geeksforgeeks.org/python-variables/ 1/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Getting the Type of Variable


Scope of a Variable
Object Reference in Python
Delete a Variable Using del Keyword
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:

Variable names can only contain letters, digits and underscores (_).
A variable name cannot start with a digit.
Variable names are case-sensitive (myVar and myvar are different).
Avoid using Python keywords (e.g., if, else, for) as variable names.

Valid Example:

age = 21
_colour = "lilac"
total_score = 90

Invalid Example:

1name = "Error" # Starts with a digit


class = 10 # 'class' is a reserved keyword
user-name = "Doe" # Contains a hyphen

Assigning Values to Variables

Basic Assignment

https://www.geeksforgeeks.org/python-variables/ 2/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Variables in Python are assigned values using the = operator.

x = 5
y = 3.14
z = "Hi"

Dynamic Typing

Python variables are dynamically typed, meaning the same variable can
hold different types of values during execution.

x = 10
x = "Now a string"

Multiple Assignments
Python allows multiple variables to be assigned values in a single line.

Assigning the Same Value

Python allows assigning the same value to multiple variables in a single


line, which can be useful for initializing variables with the same value.

a = b = c = 100
print(a, b, c)

Output

100 100 100

Assigning Different Values

We can assign different values to multiple variables simultaneously,


making the code concise and easier to read.

x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output

https://www.geeksforgeeks.org/python-variables/ 3/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

1 2.5 Python

Type Casting a Variable


Type casting refers to the process of converting the value of one data
type into another. Python provides several built-in functions to facilitate
casting, including int(), float() and str() among others.

Basic Casting Functions

int() - Converts compatible values to an integer.


float() - Transforms values into floating-point numbers.
str() - Converts any data type into a string.

Examples of Casting:

# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string

# Display results
print(n)
print(f)
print(s2)

Output

10
5.0
25

Getting the Type of Variable


In Python, we can determine the type of a variable using the type()
function. This built-in function returns the type of the object passed to
it.

https://www.geeksforgeeks.org/python-variables/ 4/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Example Usage of type()

# Define variables with different data types


n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True

# Get and print the type of each variable


print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))

Output

<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>

Scope of a Variable
There are two methods how we define scope of a variable in python
which are local and global.

Local Variables:

Variables defined inside a function are local to that function.

def f():
a = "I am local"
print(a)

f()

https://www.geeksforgeeks.org/python-variables/ 5/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

# print(a) # This would raise an error since 'local_var' is


not accessible outside the function

Output

I am local

Global Variables:

Variables defined outside any function are global and can be accessed
inside functions using the global keyword.

a = "I am global"

def f():
global a
a = "Modified globally"
print(a)

f()
print(a)

Output

Modified globally
Modified globally

Object Reference in Python


Let us assign a variable x to value 5.

x = 5

https://www.geeksforgeeks.org/python-variables/ 6/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

When x = 5 is executed, Python creates an object to represent the value


5 and makes x reference this object.

Now, if we assign another variable y to the variable x.

y = x

Explanation:

Python encounters the first statement, it creates an object for the


value 5 and makes x reference it. The second statement creates y and
references the same object as x, not x itself. This is called a Shared
Reference, where multiple variables reference the same object.

Now, if we write

x = 'Geeks'

Python creates a new object for the value "Geeks" and makes x reference
this new object.

https://www.geeksforgeeks.org/python-variables/ 7/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Explanation:

The variable y remains unchanged, still referencing the original object


5.

If we now assign a new value to y:

y = "Computer"

Python creates yet another object for "Computer" and updates y to


reference it.
The original object 5 no longer has any references and becomes
eligible for garbage collection.

Key Takeaways:
Python variables hold references to objects, not the actual objects
themselves.
Reassigning a variable does not affect other variables referencing the
same object unless explicitly updated.

https://www.geeksforgeeks.org/python-variables/ 8/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Delete a Variable Using del Keyword


We can remove a variable from the namespace using the del keyword.
This effectively deletes the variable and frees up the memory it was
using.
Example:

# Assigning value to variable


x = 10
print(x)

# Removing the variable using del


del x

# Trying to print x after deletion will raise an error


# print(x) # Uncommenting this line will raise NameError: name 'x
defined

Explanation:
del x removes the variable x from memory.
After deletion, trying to access the variable x results in a NameError,
indicating that the variable no longer exists.

Practical Examples

1. Swapping Two Variables

Using multiple assignments, we can swap the values of two variables


without needing a temporary variable.

a, b = 5, 10
a, b = b, a
print(a, b)

Output

10 5

2. Counting Characters in a String

https://www.geeksforgeeks.org/python-variables/ 9/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Assign the results of multiple operations on a string to variables in one


line.

word = "Python"
length = len(word)
print("Length of the word:", length)

Output

Length of the word: 6

Python Quiz:

Python Variable Quiz

Related Posts:

Global and Local Variables in Python


Scope of Variables
int() in Python
float() in Python
str() in Python
Assign function to a Variable in Python
Insert a Variable into a String in Python
Type Casting in Python

Recommended Problems:

Type Conversion
TypeCast And Double It
Swap The Numbers
Sum of N Numbers
Int Str

Python Variables - Python

What is the scope of a variable in Python?

https://www.geeksforgeeks.org/python-variables/ 10/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

The scope of a variable determines where it can be accessed.


Local variables are scoped to the function in which they are
defined, while global variables can be accessed throughout the
program.

Can we change the type of a variable after assigning it?

Yes, Python allows dynamic typing. A variable can hold a value of


one type initially and be reassigned a value of a different type
later.

What happens if we use an undefined variable?

Using an undefined variable raises a NameError. Always initialize


variables before use.

How can we delete a variable in Python?

We can delete a variable in Python using the del keyword:

x = 10
del x
#print(x) # Raises a NameError since 'x' has been deleted

Comment More info


Next Article

Campus Training Program


Python Operators

Similar Reads

Python Syllabus
Here’s a straight-to-the-point breakdown of what a python course covers
from the basics to advanced concepts like data handling, automation and…

15+ min read

https://www.geeksforgeeks.org/python-variables/ 11/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Python String
A string is a sequence of characters. Python treats anything inside quotes
as a string. This includes letters, numbers, and symbols. Python has no…

15+ min read

Tuples in Python
Python Tuple is a collection of objects separated by commas. A tuple is
similar to a Python list in terms of indexing, nested objects, and repetitio…

15+ min read

Python Testing
Python testing is a fundamental aspect of software development that
plays a crucial role in ensuring the reliability, correctness, and…

15+ min read

Python Quiz
These Python quiz questions are designed to help you become more
familiar with Python and test your knowledge across various topics. Fro…

13 min read

Python Virtual Machine


The Python Virtual Machine (VM) is a crucial component of the Python
runtime environment. It executes Python bytecode, which is generated…

15+ min read

Python vs Cpython
Python is a high-level, interpreted programming language favored for its
readability and versatility. It's widely used in web development, data…

15+ min read

Python Version History


Python, one of the most popular programming languages today, has a rich
history of development and evolution. From its inception in the late 1980…
https://www.geeksforgeeks.org/python-variables/ 12/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

15+ min read

Python Data Structures


Data Structures are a way of organizing data so that it can be accessed
more efficiently depending upon the situation. Data Structures are…

15+ min read

Print Single and Multiple variable in Python


In Python, printing single and multiple variables refers to displaying the
values stored in one or more variables using the print() function.Let's loo…

9 min read

Corporate & Communications Address:


A-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)

Registered Address:
K 061, Tower K, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305

Advertise with us

Company Explore
About Us Job-A-Thon
Legal Offline Classroom Program
Privacy Policy DSA in JAVA/C++
Careers Master System Design
In Media Master CP

https://www.geeksforgeeks.org/python-variables/ 13/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Contact Us Videos
Corporate Solution
Campus Training Program

Tutorials DSA
Python Data Structures
Java Algorithms
C++ DSA for Beginners
PHP Basic DSA Problems
GoLang DSA Roadmap
SQL DSA Interview Questions
R Language Competitive Programming
Android

Data Science & ML Web Technologies


Data Science With Python HTML
Machine Learning CSS
ML Maths JavaScript
Data Visualisation TypeScript
Pandas ReactJS
NumPy NextJS
NLP NodeJs
Deep Learning Bootstrap
Tailwind CSS

Python Tutorial Computer Science


Python Examples GATE CS Notes
Django Tutorial Operating Systems
Python Projects Computer Network
Python Tkinter Database Management System
Web Scraping Software Engineering
OpenCV Tutorial Digital Logic Design
Python Interview Question Engineering Maths

DevOps System Design


Git High Level Design
AWS Low Level Design
Docker UML Diagrams
Kubernetes Interview Guide
Azure Design Patterns
GCP OOAD
DevOps Roadmap System Design Bootcamp
Interview Questions

School Subjects Databases


Mathematics SQL
Physics MYSQL
Chemistry PostgreSQL
Biology PL/SQL

https://www.geeksforgeeks.org/python-variables/ 14/15
6/10/25, 10:00 AM Python Variables - GeeksforGeeks

Social Science MongoDB


English Grammar

Preparation Corner More Tutorials


Company-Wise Recruitment Process Software Development
Aptitude Preparation Software Testing
Puzzles Product Management
Company-Wise Preparation Project Management
Linux
Excel
All Cheat Sheets

Courses Programming Languages


IBM Certification Courses C Programming with Data Structures
DSA and Placements C++ Programming Course
Web Development Java Programming Course
Data Science Python Full Course
Programming Languages
DevOps & Cloud

Clouds/Devops GATE 2026


DevOps Engineering GATE CS Rank Booster
AWS Solutions Architect Certification GATE DA Rank Booster
Salesforce Certified Administrator Course GATE CS & IT Course - 2026
GATE DA Course 2026
GATE Rank Predictor

@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved

https://www.geeksforgeeks.org/python-variables/ 15/15

You might also like