Skip to Content
Course content

2.1 Variables and Data Types

Understanding variables and data types is crucial for writing functional and efficient Python programs. In Python, variables are used to store data, and each variable is associated with a data type that defines the kind of value it can hold. Python is dynamically typed, meaning you don't have to declare a variable's type explicitly, as Python will automatically determine the type based on the value assigned to the variable.

1. What are Variables?

A variable in Python is a symbolic name that is bound to a specific value. When you assign a value to a variable, you are essentially creating a reference to that value, which can be used throughout your code. Variables allow you to store and manipulate data in your program.

Example:

# Assigning a value to a variable
x = 10
name = "Alice"
is_active = True

In the example:

  • x is a variable holding the integer value 10.
  • name is a variable holding the string value "Alice".
  • is_active is a variable holding the boolean value True.

2. Naming Variables

Python has rules and conventions for naming variables:

  • Must start with a letter (a-z, A-Z) or an underscore (_).
  • Can contain letters, numbers, and underscores.
  • Cannot start with a number.
  • Case-sensitive: myVariable and myvariable are different variables.

Example:

my_variable = 42  # Valid
myVar123 = 10      # Valid
2nd_variable = 5   # Invalid (cannot start with a number)

3. Data Types in Python

Python supports several built-in data types that categorize the type of data a variable can hold. These data types include:

a. Numeric Types

  • int: Integer type. Used for whole numbers, both positive and negative, without a decimal point.
    • Example: x = 10
  • float: Floating-point type. Used for numbers with a decimal point.
    • Example: price = 19.99
  • complex: Complex number type, which consists of a real and imaginary part.
    • Example: z = 3 + 5j

b. Sequence Types

  • str: String type. Used for text or a sequence of characters. Strings are enclosed in either single (') or double (") quotes.
    • Example: greeting = "Hello, World!"
  • list: A list is an ordered collection of items that can be of any type, including numbers, strings, or other lists. Lists are mutable (can be changed after creation).
    • Example: fruits = ["apple", "banana", "cherry"]
  • tuple: A tuple is similar to a list, but it is immutable (cannot be modified after creation). It is defined by enclosing elements in parentheses (()).
    • Example: coordinates = (4, 5)
  • range: Represents a sequence of numbers, typically used in loops. It is often used to generate numbers in a given range.
    • Example: r = range(0, 10)

c. Mapping Type

  • dict: A dictionary is an unordered collection of key-value pairs. It allows you to store data by associating a unique key with a corresponding value.
    • Example: student = {"name": "Alice", "age": 21, "major": "Computer Science"}

d. Set Types

  • set: A set is an unordered collection of unique elements. Sets are used to store multiple items in a single variable but do not allow duplicates.
    • Example: numbers = {1, 2, 3, 4, 5}
  • frozenset: An immutable version of a set, meaning the elements cannot be modified after creation.
    • Example: frozen_numbers = frozenset([1, 2, 3])

e. Boolean Type

  • bool: Boolean type used to represent one of two values: True or False.
    • Example: is_valid = True

f. Binary Types

  • bytes: Immutable sequence of bytes.
    • Example: b = bytes([65, 66, 67])
  • bytearray: A mutable sequence of bytes.
    • Example: b_array = bytearray([65, 66, 67])
  • memoryview: A view object that allows Python's buffer protocol to access the memory of other binary objects without copying.
    • Example: m = memoryview(b_array)

4. Dynamic Typing

Python uses dynamic typing, which means the type of a variable is determined at runtime. This allows for greater flexibility but requires the developer to be cautious about type mismatches.

Example:

x = 10         # x is an integer
x = "Hello"    # Now x is a string (variable type changes dynamically)

In this case, x initially holds an integer but later holds a string without requiring any special declaration or change in syntax.

5. Type Conversion (Casting)

Sometimes, you may need to convert one data type to another. Python provides built-in functions for type conversion.

  • int(): Converts to an integer.
    • Example: x = int("10") # x is now 10
  • float(): Converts to a floating-point number.
    • Example: x = float("10.5") # x is now 10.5
  • str(): Converts to a string.
    • Example: x = str(10) # x is now '10'
  • list(), tuple(), set(): Used for converting sequences into lists, tuples, or sets, respectively.

6. Summary

  • Variables in Python store data and can be assigned without explicitly defining their type.
  • Python has various data types, including numeric types (int, float, complex), sequence types (str, list, tuple), mapping types (dict), set types (set, frozenset), and boolean type (bool).
  • Python is dynamically typed, so you don't need to declare a variable's type in advance.
  • Type conversion can be done using functions like int(), float(), str(), etc.
  • Always choose the appropriate data type based on the kind of data you need to store and process in your program.

Understanding how to use variables and data types effectively will help you write more efficient and error-free Python code.

Commenting is not enabled on this course.