Variables in Python

ayyuba ahmadayyuba ahmad
4 min read

Variables in Python are fundamental for storing and manipulating data. Understanding variables is crucial for writing effective Python programs.

What is a Variable?

A variable in Python is a symbolic name associated with a value and whose associated value can be changed. Think of a variable as a container for data.

Creating Variables

In Python, you don’t need to declare a variable before using it. You create a variable by simply assigning a value to it:

Example

x = 10

name = "Alice"

Here, x is an integer variable with a value of 10, and name is a string variable with a value of "Alice".

Variable Naming Rules

Must start with a letter (a-z, A-Z) or an underscore (_).

Followed by letters, numbers, or underscores.

Case-sensitive (myVar and myvar are different).

Cannot be a reserved word (e.g., class, for, if).

Valid examples:

my_var = 10

_my_var = 20

var2 = "Hello"

Invalid examples:

2var = 10 # Starts with a number

my-var = 20 # Contains a hyphen

class = "Hello" # Uses a reserved

Data Types

Variables can store different types of data:

Integer: Whole numbers.

Example

age = 25

Float: Numbers with a decimal point.

Example

pi = 3.14

String: Sequence of characters.

Example

greeting = "Hello, World!"

Boolean: True or False.

Example

is_student = True

List: Ordered, mutable collection.

Example

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

Tuple: Ordered, immutable collection.

Example

coordinates = (10, 20)

Dictionary: Unordered collection of key-value pairs.

Example

student = {"name": "John", "age": 21}

Variable Assignment

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

Example

a, b, c = 1, 2, 3

Or assign the same value to multiple variables:

Example

x = y = z = 100

Dynamic Typing

Python is dynamically typed, meaning the type of a variable is interpreted at runtime and can change:

Example

var = 10 # var is an integer

var = "Hi" # var is now a string

TypeCasting

To explicitly convert between types, you use type casting:

Example

x = int(2.8) # x will be 2

y = float("3.14") # y will be 3.14

z = str(123) # z will be '123'

Variable Scope

The scope of a variable determines its accessibility within different parts of the code. There are two main scopes in Python:

Local Scope: Variables declared inside a function.

Example

Local Scope: Variables declared inside a function.

def my_function():
    x = 10  # Local variable
    print(x)

Here, x is accessible only within my_function.

Global Scope: Variables declared outside any function.

Example

x = 10  # Global variable

def my_function():
    print(x)  # Accessing global variable

Here, x is accessible inside my_function as well.

To modify a global variable inside a function, use the global keyword:

Example

x = 10

def my_function():
    global x
    x = 20

my_function()
print(x)  # Output will be 20

Constants

Python doesn’t have built-in constant types, but you can use a naming convention (all uppercase letters) to indicate a variable should not be changed:

Example

PI = 3.14159

This is a convention, not a rule enforced by Python.

Best Practices for Using Variables

Meaningful Names: Use descriptive names to make the code self-explanatory.

Example

age = 25 # Clear

a = 25 # Not clear

Avoid Single-letter Names: Except for common cases like i in loops.

Consistency: Use consistent naming conventions (e.g., snake_case).

Avoid Using Reserved Words: Ensure variable names do not clash with Python keywords.

Variable Operations

Variables can be manipulated using various operators:

Arithmetic Operators:

Example

x = 10

y = 5

print(x + y) # Addition

print(x - y) # Subtraction

print(x * y) # Multiplication

print(x / y) # Division

print(x % y) # Modulus

print(x ** y) # Exponentiation

Assignment Operators:

Example

x = 10

x += 5 # Equivalent to x = x + 5

x -= 5 # Equivalent to x = x - 5

x *= 5 # Equivalent to x = x * 5

x /= 5 # Equivalent to x = x / 5

ComparisonOperators:

Example

x = 10

y = 5

print(x == y) # Equal to

print(x != y) # Not equal to

print(x > y) # Greater than

print(x < y) # Less than

print(x >= y) # Greater than or equal to

print(x <= y) # Less than or equal to

Logical Operators:

Example

x = True

y = False

print(x and y) # Logical AND

print(x or y) # Logical OR

print(not x) # Logical NOT

Identity Operators:

Example

x = ["apple", "banana"]

y = ["apple", "banana"]

z = x

print(x is z) # True, because z is the same object as x

print(x is y) # False, because x and y are different objects

print(x == y) # True, because x and y have the same content

Membership Operators:

Example

fruits = ["apple", "banana"]

print("banana" in fruits) # True

print("cherry" not in fruits) # True

Conclusion

Variables in Python are versatile and allow for dynamic and flexible programming. Understanding the different types, scope, naming conventions, and best practices is crucial for writing efficient and readable code. By mastering variables, you lay a strong foundation for deeper Python programming concepts.

0
Subscribe to my newsletter

Read articles from ayyuba ahmad directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

ayyuba ahmad
ayyuba ahmad