Variables and Data Types in Python
Overview
This lesson revisits and delves deeper into variables and data types in Python. Understanding variables and the various data types available in Python is crucial for effective programming. By the end of this lesson, you will have a solid understanding of how to use variables and the different data types to store and manipulate data in your Python programs.
Introduction
Variables in Python are used to store information that can be referenced and manipulated in a program. They are created by assigning a value to a variable name. Python is dynamically typed, which means you don’t need to declare the type of variable while defining it.
Variables
- Naming: Variable names must start with a letter or an underscore character, followed by letters, numbers, or underscores.
- Assignment: Use the
=
operator to assign values to variables. For example,x = 10
assigns the value10
tox
. - Dynamic Typing: The type of a variable can change based on the data assigned to it. For example,
x = 10
makesx
an integer, butx = "Hello"
changesx
to a string.
Basic Data Types
- Numeric Types:
- Integer (
int
): Whole numbers, positive or negative. Example:age = 25
- Float (
float
): Numbers with a decimal point. Example:height = 5.9
- Complex (
complex
): Numbers with a real and imaginary part. Example:z = 2 + 3j
- Integer (
- Boolean Type (
bool
):- Represents truth values:
True
orFalse
. - Can be the result of comparisons or logical operations.
- Represents truth values:
- Sequence Types:
- String (
str
): A sequence of characters. Example:name = "Alice"
- List: An ordered collection of items. Example:
fruits = ["apple", "banana", "cherry"]
- Tuple: An ordered, immutable collection of items. Example:
coordinates = (10, 20)
- String (
- Set Types:
- Set: An unordered collection of unique items. Example:
languages = {"Python", "Java", "C++"}
- Frozen Set (
frozenset
): An immutable version of a set.
- Set: An unordered collection of unique items. Example:
- Mapping Type:
- Dictionary (
dict
): An unordered collection of key-value pairs. Example:person = {"name": "Alice", "age": 25}
- Dictionary (
Type Conversion
Python allows for explicit conversion of data types, using functions like int()
, float()
, str()
, etc.
- Convert to integer:
int("10")
results in10
. - Convert to string:
str(10)
results in"10"
. - Convert to list:
list("abc")
results in['a', 'b', 'c']
.
Mutable vs Immutable Types
- Mutable: Objects whose value can change. Examples include lists and dictionaries.
- Immutable: Objects whose value is unchangeable once they are created. Examples include strings, tuples, and numbers.
Conclusion
Variables and data types are foundational concepts in Python programming. They enable you to store, manipulate, and retrieve data efficiently. Understanding the characteristics of each data type and when to use them will enhance your ability to write effective Python code.