Python Variables Explained with Examples

Python Variables are containers for storing data values. Unlike some other programming languages, Python has no command for declaring a variable – a variable is created the moment you first assign a value to it.

Python Variables Assignment

# Creating a variable and assigning a value
message = "Hello, Python!"
number = 42
pi_value = 3.14159

print(message)  # Output: Hello, Python!
print(number)   # Output: 42
print(pi_value) # Output: 3.14159

Python Variables Naming Rules

  • Must start with a letter or underscore
  • Can only contain letters, numbers, and underscores
  • Are case-sensitive (age, Age, and AGE are different variables)
# Valid variable names
my_variable = "valid"
_variable = "also valid"
variable2 = "still valid"

# Invalid variable names (would cause errors)
# 2variable = "invalid"
# my-variable = "invalid"
# my variable = "invalid"

Python Variables Dynamic Typing

Python variables can change type after they’ve been set.

x = 4       # x is an integer
x = "Sally" # x is now a string
print(x)    # Output: Sally

Python Variables Multiple Assignment

# Assigning multiple variables in one line
a, b, c = "Apple", "Banana", "Cherry"
print(a)  # Output: Apple
print(b)  # Output: Banana
print(c)  # Output: Cherry

# Assigning the same value to multiple variables
x = y = z = "Orange"
print(x)  # Output: Orange
print(y)  # Output: Orange
print(z)  # Output: Orange

Python Variables Types

Python has various data types for variables:

# String
name = "Alice"

# Integer
age = 25

# Float
height = 5.9

# Boolean
is_student = True

# List
fruits = ["apple", "banana", "cherry"]

# Tuple
coordinates = (10.0, 20.0)

# Dictionary
person = {"name": "Bob", "age": 30}

# You can check the type with type()
print(type(name))       # Output: <class 'str'>
print(type(age))        # Output: <class 'int'>
print(type(is_student)) # Output: <class 'bool'>

Python Variables Global vs Local

# Global variable
global_var = "I'm global"

def my_function():
    # Local variable
    local_var = "I'm local"
    print(local_var)      # Works fine
    print(global_var)     # Can access global variables
    
my_function()

print(global_var)         # Works fine
# print(local_var)        # Would cause error - local_var not defined here

Python variables are fundamental to Python programming, allowing you to store and manipulate data throughout your code.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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