Search This Blog

Variables and Data Types in Python

 

Variables and Data Types in Python

In Python, variables are used to store data values, and Python’s dynamic typing makes it easy to work with different types of data without having to declare them explicitly. In this guide, we’ll cover how variables work and the common data types in Python.


1. Variables in Python

A variable in Python is a name that holds a value. You can assign a value to a variable using the = operator, and that value can be of any data type.

Variable Assignment

In Python, you simply assign a value to a variable without declaring its type:

x = 5          # x is an integer
name = "Alice" # name is a string
  • Dynamic Typing: Python automatically determines the type of a variable based on the assigned value. You can change the type of a variable simply by assigning it a new value.

    x = 10      # x is an integer
    x = "Hello" # x is now a string
    

Naming Variables

  • Start with a letter or underscore (_), not a number.
  • Case-sensitive: Name and name are different variables.
  • Avoid using Python reserved keywords (like class, for, if).

Example of good variable names:

age = 25
first_name = "John"
is_active = True

2. Data Types in Python

Python has several built-in data types that can hold different kinds of information. Here are some of the most commonly used ones:

Numeric Data Types

  1. Integer (int): Represents whole numbers, positive or negative, without decimals.

    x = 10
    y = -5
    
  2. Float (float): Represents decimal (floating-point) numbers.

    price = 19.99
    temperature = -3.5
    
  3. Complex (complex): Represents complex numbers with a real and imaginary part.

    z = 3 + 5j
    

String (str)

Strings are sequences of characters, created using single quotes ('), double quotes ("), or triple quotes for multi-line strings (''' or """).

greeting = "Hello, World!"
quote = '''This is a
multi-line string'''
  • Strings are immutable, meaning they can’t be changed once created.

Boolean (bool)

Booleans represent two values: True or False. They’re often used in conditions and comparisons.

is_active = True
is_logged_in = False

NoneType

None represents the absence of a value and is often used as a placeholder.

result = None

Sequence Types

  1. List (list): An ordered, mutable collection that can hold any data type.

    fruits = ["apple", "banana", "cherry"]
    fruits[0] = "orange"  # Lists are mutable
    
  2. Tuple (tuple): An ordered, immutable collection. Once created, values cannot be changed.

    dimensions = (1920, 1080)
    
  3. Range (range): Represents a sequence of numbers, often used in loops.

    numbers = range(5)  # Creates a range from 0 to 4
    

Mapping Type

Dictionary (dict): A collection of key-value pairs, where each key is unique.

student = {
    "name": "Alice",
    "age": 20,
    "is_enrolled": True
}
print(student["name"])  # Access value by key

Set Types

  1. Set (set): An unordered collection of unique items.

    unique_numbers = {1, 2, 3, 4, 4}  # Duplicates are removed
    
  2. Frozen Set (frozenset): An immutable version of a set.

    fs = frozenset([1, 2, 3])
    

3. Type Conversion

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

x = 10         # int
y = str(x)     # Convert to string
z = float(x)   # Convert to float

4. Checking Data Types

Use the type() function to check the data type of a variable.

x = 5
print(type(x))  # Output: <class 'int'>

Example Code with Variables and Data Types

# Integer
age = 30

# Float
height = 5.9

# String
name = "Alice"

# Boolean
is_student = True

# List
scores = [95, 88, 76]

# Tuple
coordinates = (10, 20)

# Dictionary
person = {"name": "Alice", "age": 30}

# Set
unique_numbers = {1, 2, 3}

# Display types
print(type(age))          # <class 'int'>
print(type(height))       # <class 'float'>
print(type(name))         # <class 'str'>
print(type(is_student))   # <class 'bool'>
print(type(scores))       # <class 'list'>
print(type(coordinates))  # <class 'tuple'>
print(type(person))       # <class 'dict'>
print(type(unique_numbers)) # <class 'set'>

Summary

Python’s flexible variables and data types make it easy to handle various types of data. Understanding these types and their properties is essential for writing efficient, readable, and effective Python code.

Popular Posts