Variables in Python
Introduction
- Variables act like containers in programming.
- Similar to kitchen containers used to store different types of food items, variables store data in programming.
- In Python, variables allow us to store different types of data in memory (RAM).
Data Types
Example of using variables in Python:
A = 1
print(A) # Outputs: 1
- This stores
1
in memory and assigns the address to A
.
- The variable
A
can now be used to refer to the value 1
.
Changing Variable Values
- We can change the value a variable holds.
A = 1
A = 2 # A now holds the value 2
String Variables
B = "Hello"
print(B) # Outputs: Hello
- Using double quotes to define string data.
Data Type Importance
- Variable data types in Python include:
- Integers (e.g.,
A = 1
)
- Strings (e.g.,
B = "Hello"
)
- Floats (e.g.,
C = 1.1
)
- Complex numbers (e.g.,
D = 4 + 3j
)
- Booleans (e.g.,
True
or False
)
- Lists and Tuples
- Dictionaries
- Data type is essential for performing operations on variables.
- Mismatched data types (e.g., adding a string to an integer) will cause errors.
Built-in Data Types in Python
Numeric Types
- Integer: Whole numbers (Example:
1
, 2
)
- Float: Decimal numbers (Example:
1.1
, 3.14
)
- Complex: Numbers with real and imaginary parts (Example:
4 + 3j
)
String
- Text data enclosed in quotes.
text = "Hello World"
Boolean
can_drive = True
Lists
- Ordered collection of elements which can be of different data types.
my_list = [1, "Hello", 3.14]
- Mutable, meaning their content can be changed.
Tuples
- Ordered collection similar to lists but immutable (cannot change elements once defined).
my_tuple = (1, "Hello", 3.14)
Dictionaries
- Collection of key-value pairs.
my_dict = {"name": "Sakshi", "age": 28}
- Allows quick look-ups of elements based on keys.
Notes on Mutability
- Mutable: Objects that can be changed. Example: Lists.
- Immutable: Objects that cannot be changed. Example: Tuples.
- Mutability helps in distinguishing the behavior and usage of different data structures.
Everything is an Object
- In Python, everything is treated as an object. This includes basic data types like integers, strings as well as more complex data types.
Example Code
# Variable and Type Examples
A = 1
B = "Harry"
print(A) # 1
print(B) # Harry
print(type(A)) # <class 'int'>
print(type(B)) # <class 'str'>
Conclusion
- Variables are foundational in Python programming, allowing us to store and manipulate different kinds of data effectively.
- Understanding variable types and mutability is crucial for writing efficient and error-free code.