Python Variables with Examples and Output

Variables in Python are used to store data values. You can think of a variable as a container for holding information. Python is dynamically typed, which means you don’t need to declare a variable’s type—Python determines it automatically.

What are Python Variables?

A variable is created the moment you assign a value to it. In Python, you can assign different types of data to variables such as integers, strings, floats, and booleans.

Syntax for Variable Declaration:

variable_name = value

1. Creating Variables

Python allows you to create variables and assign values directly.

Example: Creating Variables

# Assigning values to variables
name = "Dharmender"
age = 30
height = 5.9
is_student = False

# Printing variable values
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is Student:", is_student)

Output:

Name: Dharmender
Age: 30  
Height: 5.9  
Is Student: False  

2. Variable Naming Rules

  • Must start with a letter or an underscore (_).
  • Cannot start with a number.
  • Can only contain letters, numbers, and underscores.
  • Case-sensitive (name and Name are different).

Example: Valid and Invalid Variable Names

# Valid variable names
first_name = "Dharmender"
_age = 25
score1 = 90

# Invalid variable names (uncomment to see the errors)
# 1st_name = "Amit"    # Error: cannot start with a number
# first-name = "Mayank"  # Error: hyphens are not allowed

3. Multiple Variable Assignment

You can assign values to multiple variables in a single line.

Example: Multiple Variable Assignment

x, y, z = 10, 20, 30
print("x:", x, "y:", y, "z:", z)

# Assigning the same value to multiple variables
a = b = c = 100
print("a:", a, "b:", b, "c:", c)

Output:

x: 10 y: 20 z: 30  
a: 100 b: 100 c: 100  

4. Changing Variable Type

Python allows you to change the data type of a variable at any time.

Example: Changing Variable Type

value = 10   # Integer
print("Initial value:", value)

value = "Python"  # String
print("Updated value:", value)

Output:

Initial value: 10  
Updated value: Python  

5. Global and Local Variables

Variables created inside a function are local, while those created outside are global.

Example: Global and Local Variables

x = 10  # Global variable

def my_function():
    x = 5  # Local variable
    print("Local x:", x)

my_function()
print("Global x:", x)

Output:

Local x: 5  
Global x: 10  

Python variables are simple yet powerful. Understanding how to create, assign, and manipulate variables is essential for writing clean and effective code. Mastering variables will set a strong foundation for more advanced Python concepts.

Keep Learning 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *