Variables and Data Types

Loading

Introduction to Variables in Python

A variable is a symbolic name that refers to a value. In Python, variables are dynamically typed, meaning you do not need to declare the type explicitly. The interpreter determines the type at runtime based on the assigned value.

Declaring and Assigning Variables

In Python, assigning a value to a variable is straightforward:

x = 10  # Integer
name = "Alice" # String
is_active = True # Boolean
  • The = operator is used to assign values to variables.
  • The type of the variable is inferred from the assigned value.

Rules for Naming Variables

  1. Must start with a letter (a-z, A-Z) or an underscore _.
  2. Cannot start with a digit.
  3. Can only contain alphanumeric characters and underscores (_).
  4. Case-sensitive (age and Age are different variables).
  5. Cannot use Python keywords as variable names (e.g., if, class, def).

Example of valid and invalid variable names:

_valid_variable = 10  
validVariable2 = "Hello"
2invalidVar = 5 # Invalid: Cannot start with a number
class = "Math" # Invalid: 'class' is a reserved keyword

Data Types in Python

Python has several built-in data types categorized into:

  1. Numeric Types (int, float, complex)
  2. Text Type (str)
  3. Boolean Type (bool)
  4. Sequence Types (list, tuple, range)
  5. Set Types (set, frozenset)
  6. Mapping Type (dict)
  7. Binary Types (bytes, bytearray, memoryview)
  8. None Type (NoneType)

1. Numeric Types

a) Integer (int)

  • Whole numbers without decimal points.
  • Example:
num1 = 100  
num2 = -50
print(type(num1)) # Output: <class 'int'>

b) Floating-Point Number (float)

  • Numbers with decimal points or in exponential form.
  • Example:
pi = 3.14  
large_number = 1.5e3 # Equivalent to 1500.0
print(type(pi)) # Output: <class 'float'>

c) Complex Numbers (complex)

  • Numbers with a real and an imaginary part.
  • Represented as a + bj.
  • Example:
z = 3 + 4j  
print(type(z)) # Output: <class 'complex'>

2. Text Type

String (str)

  • A sequence of characters enclosed in single (') or double (") quotes.
  • Strings are immutable (cannot be changed after creation).
  • Example:
message = "Hello, World!"  
print(type(message)) # Output: <class 'str'>

String Operations

text = "Python"
print(text[0]) # Output: 'P' (Indexing)
print(text[-1]) # Output: 'n' (Negative Indexing)
print(text[0:3]) # Output: 'Pyt' (Slicing)
print(text.upper()) # Output: 'PYTHON'

3. Boolean Type

  • True or False values.
  • Used in conditional statements.
  • Example:
is_python_fun = True  
is_java_difficult = False
print(type(is_python_fun)) # Output: <class 'bool'>

4. Sequence Types

a) List

  • Ordered, mutable (changeable) collection.
  • Defined using square brackets [ ].
  • Example:
fruits = ["Apple", "Banana", "Cherry"]  
fruits.append("Mango") # Adding an item
print(fruits) # Output: ['Apple', 'Banana', 'Cherry', 'Mango']

b) Tuple

  • Ordered, immutable collection.
  • Defined using parentheses ( ).
  • Example:
coordinates = (10, 20)  
print(type(coordinates)) # Output: <class 'tuple'>

c) Range

  • Generates sequences of numbers.
  • Example:
numbers = range(5)  # Generates numbers from 0 to 4
print(list(numbers)) # Output: [0, 1, 2, 3, 4]

5. Set Types

a) Set

  • Unordered collection of unique elements.
  • Example:
unique_numbers = {1, 2, 3, 3, 4}  
print(unique_numbers) # Output: {1, 2, 3, 4}

b) Frozenset

  • Immutable version of a set.
  • Example:
immutable_set = frozenset([1, 2, 3])  

6. Mapping Type

Dictionary (dict)

  • Stores key-value pairs.
  • Example:
student = {"name": "Alice", "age": 20, "grade": "A"}  
print(student["name"]) # Output: Alice

7. Binary Types

a) Bytes

  • Immutable sequence of bytes.
  • Example:
byte_data = b"Hello"  
print(type(byte_data)) # Output: <class 'bytes'>

b) Bytearray

  • Mutable version of bytes.
  • Example:
mutable_bytes = bytearray(5)  

c) Memoryview

  • Provides a view over a byte sequence.
  • Example:
memory_data = memoryview(b"Python")  

8. None Type

None (NoneType)

  • Represents the absence of a value.
  • Example:
value = None  
print(type(value)) # Output: <class 'NoneType'>

Type Conversion (Type Casting)

Python allows conversion between data types using built-in functions:

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

print(type(y)) # Output: <class 'str'>
print(type(z)) # Output: <class 'float'>

Leave a Reply

Your email address will not be published. Required fields are marked *