What Are Variables in Python?

What Are Variables?

A variable is a container or label that stores information and data for later use. Imagine, it’s a box with a specific name, you can put something inside it, like a number, text, or list and use it whenever you need.

Characteristics of Python Variables:

1) No Need to Declare Type (Dynamic Typing)

C or Java languages need a type of value, but here you don’t need to tell Python whether a variable will hold an integer, string, or float, because it automatically understands what type of data you store.

For example:

x = 10        # Integer
x = "Hello" # Now it’s a string
  • Python allows you to change the data type of a variable at any time, which represents dynamic typing.

2) Variables Can Store Any Type of Data

Python variables are versatile, which means they can hold different types of values, such as:

Data TypeExampleDescription
Integernum = 5Whole numbers
Floatpi = 3.14Decimal numbers
Stringcity = “Paris”Sequence of characters
Listfruits = [“apple”, “banana”, “mango”]Collection of items
Booleanis_active = TrueTrue or False values

3) Reassignment Is Allowed In Python

You can change the value of a variable anytime during your program. It means that when you assign a new value, the old one is replaced.

For example:

score = 85
score = 90 # Reassigned new value
print(score)

Output:

90

4) Variables Act as References, Not Fixed Boxes

In Python, when you create a variable, it doesn’t store the value directly. Instead, it refers to a memory location where the value is stored. For example:

a = [1, 2, 3]
b = a
b.append(4)
print(a)

Output:

[1, 2, 3, 4]
  • Here, a and b point to the same list in memory. When you modify one, the changes reflect in the other because both refer to the same object.

Python Variable Declaration

Variable declaration is very simple and beginner-friendly, because we don’t need to use any special keyword, just assign a value to a variable name using the assignment operator (=). Python automatically understands what type of data you are storing.

Syntax:

variable_name = value

Example:

name = "Jimmy"        # A string variable
age = 28 # An integer variable
height = 6.2 # A floating-point variable
is_student = True # A boolean variable

Rules of Python Variable Naming Convention

1) Use Letters, Numbers, and Underscores: Variable names can contain letters (A–Z, a–z), numbers (0–9), and underscores (_). But they must start with a letter or an underscore, never with a number.

Valid Examples:

name = "Jimmy"
_age = 22
student_1 = "Dyna"

Invalid Examples:

1name = "Nisha"     # You cannot start with a number
@student = "Raj"  # Also you cannot use special characters like @

2) Avoid Using Python’s Reserved Keywords: Don’t use Python keywords like if, while, True or def as variable names. Python has some specific words or keywords that we can not use as variable names. For example, if, else, True, def, etc.

if = 5       # Error: 'if' is a reserved keyword
True = "Yes" # Error: 'True' cannot be reassigned

3) Python is Case-Sensitive: Python treats uppercase and lowercase letters as different. For example, name and Name are two separate variables.

name = "Denny"
Name = "John"

#Here, name and Name are two different variables

Use Descriptive Names: Choose meaningful names to make your code more readable.

4) Use Descriptive and Meaningful Names: Always pick names that clearly describe what the variable stores. It makes our code easy to read and maintain.

Bad Examples:

x = 100
y = 500

Good Examples:

customer_name = "Neha"
order_total = 500
  • You can see, we have clearly described the name of the customer. This process will help you in real-life industry projects.

Variable Reassignment in Python

You heard about variable reassignment, but what is this! reassignment means you can easily change or reassign their value anytime, even if the new value belongs to a completely different data type.

This method is one of the biggest strengths of Python because it’s a dynamically typed language.

Example: You can change a variable’s value

x = 10          # Initially an integer
x = "Python" # Now changed to a string
x = [1, 2, 3] # Reassigned to a list
print(x)

Output of this program:

[1, 2, 3]

Multiple Assignments in Python

Python provides a time-saving feature that allows you to assign multiple values to multiple variables in just one line.

Example: We can assign multiple values like this

a, b, c = 10, 20, 30
print(a, b, c)

# Output: 10 20 30

We can also assign the same value to multiple variables. This is helpful when several variables should start with the same data. For example:

x = y = z = 50
print(x, y, z)

# Output: 50 50 50
  • Here, all three variables (x, y, and z) point to the same value 50.

What Is Variable Types in Python?

We can store numbers, text, lists, or even more complex data structures in variables. Here are the lists of data types in the variable:

  • Integer (int)
  • Float (float)
  • String (str)
  • Boolean (bool)
  • List (list)
  • Dictionary (dict)

1) Integer (int)

integers are used to store whole numbers either positive and negative without any decimal point. For example:

age = 25
temperature = -10

#age holds a positive integer value.
# temperature stores a negative integer.

We will learn in further topic to use integers in mathematical operations like addition, subtraction, multiplication, and division.

2) Float (float)

A float represents a number with a decimal point, and it’s also called a floating-point number. For example:

height = 5.9
price = 99.99
  • Floats are requires when we calculates a prices, measurements, or averages.

3) String (str)

String stores a textual data, it means a sequence of characters enclosed in single (‘ ‘) or double (” “) quotes. For example:

name = "Jimmy"
message = 'Welcome to Home!'
  • Strings can include letters, numbers, and symbols.

4) Boolean

Booleans store logical values, either True or False. These data types mainly used in conditions and decision-making.

is_student = True
has_passed = False

Example:

if is_student:
    print("You are a student!")

Output:

You are a student!

5) List (list)

A list is a collection of multiple values stored in a single variable, and lists are ordered, changeable, and can hold different data types at once.

Example:

fruits = ["apple", "banana", "cherry"]
  • Lists are enclosed within square brackets [].

6) Dictionary (dict)

A dictionary stores data as key–value pairs, similar to how a real dictionary stores words. For example:

person = {
"name": "Jimmy",
"age": 25,
"city": "Paris"
}
  • Dictionaries are very useful for storing structured data, like user profiles, settings, or JSON data.

Global and Local Variables In Python

This concept is essential for writing clean and bug-free code.

What Is Variable Scope?

The scope of a variable defines where in the program that variable can be accessed or modified.

Python has two main types of variable scopes:

  • Local Scope
  • Global Scope

1) Local Variables: A local variable is a variable that only declared and used only inside the function. Once the function finishes execution, the variable is destroyed and cannot be accessed outside of it.

Example:

def greet():
name = "Jimmy" # Local variable
print("Hello, " + name)

greet()
# print(name) # This will cause an error because 'name' exists only inside the function
  • It is a local scope, which means when you try to access it outside the function, Python shows an error because it doesn’t exist in the global scope.

2) Global Variables: A global variable is defined outside any function and is accessible from anywhere in the program.

Example:

name = "Jimmy"  # Global variable

def greet():
print("Hello, " + name)

greet() # Output: Hello, Jimmy
  • In this code, the variable name is declared outside any function, so Python treats it as global.

How to modifying Global Variables Inside a Function?

We can use the global keyword to change the value of a global variable inside a function. For example:

count = 0  # Global variable

def increment():
global count
count += 1 # Modifying the global variable

increment()
print(count) # Output: 1
  • The global keyword tells Python to refer to the existing global variable instead of creating a local one.

Learn Advanced Topics About Python

Leave a Comment