Variables and Data Types

Variables and data types are fundamental concepts in Python programming. In this tutorial, we will explore how variables are used to store data and the various data types available in Python.

Variables

In Python, a variable is a name that represents a value stored in the computer’s memory. You can assign different types of data to variables, and Python will automatically determine the data type based on the assigned value.

Variable Assignment

Variable assignment is done using the equal sign (=) operator.


      # Assigning an integer to a variable
      age = 25

      # Assigning a string to a variable
      name = "John Doe"

      # Assigning a float to a variable
      pi = 3.14

      # Assigning a boolean to a variable
      is_student = True
      

Variable Naming Rules

When naming variables in Python, you need to follow certain rules:

  1. The name must start with a letter (a-z, A-Z) or an underscore (_).
  2. The rest of the name can contain letters, digits (0-9), or underscores.
  3. Variable names are case-sensitive, so age, Age, and AGE are considered different variables.

It is also advisable to use descriptive names for variables to make the code more readable and understandable.

Constant Naming Convention

A constant is a special type of variable whose value cannot be changed. However, although Python does not support constants, we still name constants in all capital letters to separate them from variables.


      PI = 3.14
      APPLE_COLOR = "Red"
      

Data Types

Python is a dynamically typed language, meaning that you don’t need to specify the data type of a variable explicitly. Python automatically determines the data type based on the assigned value. Here are some common data types in Python:

Numeric Types

Text Type

Boolean Type

Collection Types

Type Casting

You can convert variables from one data type to another using type casting.


      # Converting a float to an integer
      num_float = 3.14
      num_int = int(num_float)  # num_int will be 3

      # Converting an integer to a string
      number = 42
      number_str = str(number)  # number_str will be "42"