Python Variables

Python Variables

In Python, variables are fundamental components used to store data that can be referenced and manipulated throughout the execution of a program. A variable essentially serves as a name assigned to a specific value. Unlike many other programming languages, Python does not require you to explicitly declare the type of a variable; instead, the type is inferred from the assigned value.

Variables act as placeholders for data, allowing us to store and reuse values effectively within our programs.

Example

x = 5
name = "Samantha"
print(x)
print(name)

Output

5
Samantha

Table of Contents

  1. Rules for Naming Variables
  2. Assigning Values to Variables
  3. Multiple Assignments
  4. Casting a Variable
  5. Getting the Type of a Variable
  6. Scope of a Variable
  7. Object Reference in Python
  8. Deleting a Variable with the del Keyword
  9. Practical Examples

Rules for Naming Variables

To use variables effectively, it’s important to adhere to Python’s naming conventions:

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

Valid Examples:

age = 21
_colour = "lilac"
total_score = 90

Invalid Examples:

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

In Python, values are assigned to variables using the = operator.

x = 5
y = 3.14
z = "Hi"

Dynamic Typing

Python supports dynamic typing, meaning that the same variable can hold different types of values during execution.

x = 10
x = "Now a string"

Multiple Assignments

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

Assigning the Same Value:

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

Output

100 100 100

Assigning Different Values:

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

Output

1 2.5 Python

Casting a Variable

Casting involves converting the value of one data type into another. Python provides various built-in functions for this purpose, including int(), float(), and str().

Basic Casting Functions:

  • int(): Converts compatible values to an integer.
  • float(): Converts values into floating-point numbers.
  • str(): Converts any data type into a string.

Examples of Casting:

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

To determine the type of a variable in Python, use the type() function. This built-in function returns the type of the object passed to it.

Example Usage of type():

n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool_var = 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_var))

Output

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

Scope of a Variable

In Python, the scope of a variable can be defined as either local or global.

Local Variables:

Variables defined within a function are local to that function.

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

f()
# print(a)  # This would raise an error since 'a' 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

Object Reference in Python

When assigning a variable, such as x = 5, Python creates an object for the value 5 and makes x reference this object. If another variable, y, is assigned to x, it references the same object.

x = 5
y = x  # y references the same object as x

x = 'Geeks'  # x now references a new object

Deleting a Variable with the del Keyword

You can remove a variable from the namespace using the del keyword, freeing the memory it occupied.

x = 10
print(x)

del x

# Trying to print x after deletion will raise an error
# print(x)  # Uncommenting this line will raise NameError: name 'x' is not defined

Practical Examples

1. Swapping Two Variables

Using multiple assignments, you 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

You can 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

Frequently Asked Questions (FAQs) on Python Variables

  • What is the scope of a variable in Python?
    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

Conclusion

Understanding variables is essential for programming in Python. By following naming conventions, utilizing dynamic typing, and mastering variable scope, you can write cleaner, more efficient code. Remember to leverage comments to enhance readability and maintainability in your programs.