A Container for Data, Variables
In programming, a Variable acts as a container used to store 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 a name that points to a memory location where data or instructions are temporarily stored.
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 create it so it can be used in a program.
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, referencing a variable before assigning it a value will result in a NameError.
# 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.
Lessons in this chapter · Master the Fundamentals of Python
- 1. What is Programming and What Benefits Can You Gain from Learning It?
- 2. Coding and Viewing Your Results in Real-Time
- 3. Are There Levels in Programming Languages?
- 4. Features of Python and Simple Code Example
- 5. Reasons Why Python is Popular
- 6. Why is Indentation Important in Python?
- 7. Printing Output in Python
- 8. Getting User Input in Python
- 9. Multiple-choice quiz
- 10. Statements and Expressions
- 11. Predefined Reserved Words in Python - Keywords
- 12. How to Name Variables and Functions Sensibly
- 13. Explaining Code with Comments
- 14. What are Identifiers?
- 15. A Container for Data, Variables
- 16. Important Points When Assigning Values to Variables
- 17. Symbols for Performing Operations, Operators
- 18. Literals Representing Data
- 19. Coding Quiz - Return 10 Times the Given Number
- 20. Multiple-choice quiz
- 21. Fill-in-the-blank quiz
In Python, you have to use a var or let keyword to declare a variable.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help