Python Basics: Variables
Variables are used to store values in a program. In Python, variables can be created by assigning a value to a variable name using the equal sign:
name = "Alice"
age = 30
a, b, c = 1, 2, 3
The variable data types doesn't need to explicitly be defined when declaring it:
x = 42 # x is an integer
x = "Hello" # x is now a string
x = 3.14 # x is now a float
While the concept of variables is common across programming languages, there are some aspects that make Python's handling of variables different:
- Dynamically-typed: Python is a dynamically-typed language, which means you don't need to explicitly declare the data type of a variable. The interpreter infers the data type automatically based on the value assigned to the variable. In contrast, statically-typed languages, like Java or C++, require you to declare the variable type explicitly.
- Naming conventions: Variable names must start with a letter (a-z, A-Z) or an underscore (_), followed by letters, numbers (0-9), or underscores. They are case-sensitive, and it's recommended to use lowercase with words separated by underscores (snake_case) for readability. This is different from other languages like JavaScript, where camelCase is more common.
- No variable scope keywords: Python doesn't use keywords like
var
,let
, orconst
to declare variables like JavaScript or other languages do. In Python, you simply assign a value to a variable to create it. - Automatic memory management: Python handles memory allocation and deallocation for variables automatically using a garbage collector. In languages like C or C++, you need to manage memory allocation and deallocation manually.
- Multiple assignment: Python allows you to assign values to multiple variables simultaneously in a single line, which is not common in all programming languages.
- Immutable basic types: Some basic data types like strings, integers, and tuples are immutable. This means that once a value is assigned to a variable of these types, you cannot change the value directly. However, you can reassign the variable to a new value. In other languages, such as C or C++, you can directly modify the memory content of a variable.