A Container for Data, Variables
In programming, a Variable
is essentially a container for storing data.
You can assign a name to data to store a value, and you can modify or reference the stored value as needed.
The Meaning of Variables
A variable is basically a name that points to a location in memory (an area used to temporarily store data and instructions) for storing data.
In Python, you don't need any special keywords (e.g., var
, let
) to declare a variable. Simply use a variable name and assign a value with the equals sign (=).
my_variable = 10 # Assign 10 to the variable my_variable name = "CodeFriends" # Assign "CodeFriends" to the variable name
Declaring and Initializing Variables
To declare
a variable means to prepare the variable for use.
When declaring a variable, assigning a value to it is referred to as initialization
.
# Declare the variable my_var my_var = 10 # Initialize by assigning 10
In Python, if you declare a variable without initializing it, a NameError
will occur.
# Attempt to declare a variable without initialization x # NameError: name 'x' is not defined
Therefore, when declaring a variable in Python, you must initialize it using the equals sign (=).
Characteristics of Python Variables
-
Dynamic Typing
: The data type (the form of data like text or numbers) of a variable is determined during the program's execution, and there's no need to pre-declare the variable type. -
Reassignable
: You can change the value stored in a variable or reassign it with a value of a different type.
number = 5 # Assign an integer (number) number = "five" # Reassign with a string (text)
Coding Exercise
Try assigning the string "hello" to the variable greeting
.
In Python, you have to use a var
or let
keyword to declare a variable.
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result