In Python, variables are used to store and manipulate data. Each variable has a name and holds a value of a certain data type. Python is dynamically typed, which means you don't need to explicitly declare the data type of a variable; it is determined automatically during runtime. Let's delve into the details of variables and the various data types available in Python.


Variables:

Variables are used to store values, such as numbers, text, or other data, so they can be used and manipulated later in the program. To assign a value to a variable, you use the assignment operator ('=').

python
# Variable assignment 
age = 25 name = "Alice"


Variable names should follow certain rules:


  • They can only contain letters, numbers, and underscores ('_').
  • They must start with a letter or an underscore.
  • They are case-sensitive ('age' and 'Age' are considered different variables).


Data Types:

Python supports various data types that define the nature of the values a variable can hold. Here are some commonly used data types:


1. Numeric Types:

  • int: Integer values (e.g., '5', '-12', '1000').
  • float: Floating-point values (e.g., '3.14', '-0.5', '2.0').
  • complex: Complex numbers (e.g., '1 + 2j', '3 - 4j').


2. Text Type:

  • str: String values (e.g., ' "Hello, world!" ', ' 'Python' ', ' "123" ').


3. Boolean Type:

  • bool: Represents the truth values 'True' or 'False'.


4. Sequence Types:

  • list: Ordered collection of items (e.g., '[1, 2, 3]', '["apple", "banana", "cherry"]').
  • tuple: Similar to lists, but immutable (e.g., '(1, 2, 3)', '("a", "b", "c")').
  • range: Represents an immutable sequence of numbers (e.g., 'range(5)', 'range(2, 10, 2)').


5. Mapping Type:

  • dict: Collection of key-value pairs (e.g., '{"name": "Alice", "age": 25}').


6. Set Types:

  • set: Unordered collection of unique items (e.g., '{1, 2, 3}', '{"apple", "banana"}').
  • frozenset: Similar to sets, but immutable.


7. None Type:

  • None: Represents the absence of a value or a null value.


Type Conversion (Casting):

Python allows you to convert between different data types using type conversion functions like 'int()', 'float()', 'str()', etc.

python
age = 25 
age_as_str = str(age)        # Convert int to str 
height = "160" 
height_as_int = int(height)      # Convert str to int


Dynamic Typing:

Because Python is dynamically typed, you can reassign variables to different data types without explicit type declarations.

python
x = 5       # x is an integer 
x = "hello"       # Now x is a string


Type Checking:

You can check the data type of a variable using the 'type()' function.

python
age = 25 print(type(age))       # Output: <class 'int'>


Understanding variables and data types is crucial in programming, as it helps you manipulate and transform data effectively. By mastering these fundamentals, you lay a strong foundation for building more complex programs in Python.