Skip to main content

Introduction to Python Variables

Python Variables

Variables are used to store values that can be accessed and manipulated throughout the program.

Unlike some other programming languages, Python is dynamically typed, which means you don't need to declare the type of a variable explicitly.

Here are the key aspects of working with variables in Python:

Variable Naming

Variable names in Python can consist of letters (a-z, A-Z), digits (0-9), and underscores (_).

However, they must start with a letter or an underscore and cannot be a reserved keyword.

Python is case-sensitive, so variables myVar and myvar would be considered as two different variables.

Variable Assignment

To assign a value to a variable, you can use the assignment operator (=). The value on the right side of the = sign is assigned to the variable on the left side.

x = 10  # Assigning the value 10 to variable x
name = "John" # Assigning the string "John" to variable name

Variable Types

Python variables can hold different types of data. Some common data types include:

  • Numbers: Integers (int), floating-point numbers (float), and complex numbers (complex).
  • Strings: Ordered sequences of characters enclosed in single quotes (') or double quotes (").
  • Lists: Ordered and mutable collections of items enclosed in square brackets ([]).
  • Booleans: Represents either True or False.
  • Tuples: Ordered and immutable collections of items enclosed in parentheses (()).
  • Dictionaries: Unordered collections of key-value pairs enclosed in curly braces ({}).
  • Sets: Unordered collections of unique items enclosed in curly braces ({}).
age = 25  # Integer variable
pi = 3.14159 # Float variable
name = "John" # String variable
is_true = True # Boolean variable
fruits = ['apple', 'banana', 'orange'] # List variable
coordinates = (10, 20) # Tuple variable
student = {'name': 'Alice', 'age': 20} # Dictionary variable

Variable Reassignment

Variables can be reassigned to new values using the assignment operator.

The new value can have a different type than the previous value assigned to the variable.

x = 5  # Assigning the value 5 to variable x
x = "Hello" # Reassigning x with a string value

Variable Operations

Variables can be used in expressions and participate in various operations such as arithmetic operations, string concatenation, and more.

x = 5
y = 3
sum = x + y # Adding the values of x and y

name = "John"
greeting = "Hello, " + name # Concatenating strings

Variable Scope

The scope of a variable determines where it can be accessed within a program.

Variables declared inside a function have local scope and are only accessible within that function.

Variables declared outside of any function have global scope and can be accessed throughout the program.