Data Types & Variables - CameronAuler/python-devops GitHub Wiki

Table of Contents

Variables

A named reference to a value stored in memory. Variables do not require explicit declaration and can store different data types. Python is dynamically typed, meaning you don’t need to declare the type of a variable—it’s inferred from the assigned value.

x = 10        # Integer variable
name = "John" # String variable
pi = 3.14     # Float variable

Variable Naming Rules

  • Can contain letters (a-z, A-Z), digits (0-9), and underscores (_).
  • Cannot start with a number.
  • Cannot contain special characters like @, $, %.
  • Cannot use reserved keywords (if, def, class, etc.).
  • Case-sensitive (age and Age are different variables).

Valid Examples

user_name = "Alice"  # Snake_case (recommended)
age = 25
MAX_LIMIT = 100  # Constants (by convention, use uppercase)

Invalid Examples

1name = "John"   # ❌ Cannot start with a number
my-name = "Sam"  # ❌ Hyphens are not allowed
def = 10         # ❌ Cannot use reserved keywords

Multi-variable Assignment

Python allows assigning values to multiple variables in a single line.

a, b, c = 1, 2, 3
print(a, b, c)  # Output: 1 2 3

Same Value Multi-variable Assignment

x = y = z = 100
print(x, y, z)  # Output: 100 100 100

Constants

A named value that cannot be modified. Python does not have a built-in constant type, but by convention, uppercase names indicate constants.

PI = 3.14159
MAX_USERS = 1000

Variable Scope & Lifetime

A variable’s scope determines where it can be accessed.

  • Local Variable – Defined inside a function, accessible only within that function.
  • Global Variable – Defined outside functions, accessible everywhere.
  • Nonlocal Variable – Used in nested functions to refer to a variable in an enclosing function.

Local

x = 10  # Global variable

def my_function():
    y = 5  # Local variable
    print(y)  # Accessible inside the function

print(x)  # Accessible anywhere

Global

def modify_global():
    global x
    x = 50  # Modifies the global variable

modify_global()
print(x)  # Output: 50

Numbers

Integers (int)

Includes whole numbers: positive, negative, zero, and no decimals. Python 3 has no explicit limit on the size of an integer (apart from available memory).

x = 10       # Integer
y = -5       # Negative Integer
z = 1000000  # Large Integer
print(type(x))  # Output: <class 'int'>

Floating-point numbers (float)

Numbers with a decimal point or in exponential notation. Used for real numbers (any number that can be found on the number line).

a = 10.5    # Float
b = -3.14   # Negative Float
c = 1.2e3   # Scientific notation (1.2 × 10³)
print(type(a))  # Output: <class 'float'>

Complex Numbers (complex)

A type of number that includes both real and imaginary parts. Written as a + bj, where j is the imaginary unit.

c1 = 3 + 4j
c2 = complex(2, -3)  # Using the complex() function
print(c1.real)  # Output: 3.0
print(c1.imag)  # Output: 4.0

Strings

String Definition

Sequences of characters enclosed in quotes (' ', " ", ''' ''', """ """).

s1 = "Hello, World!"   # Double quotes
s2 = 'Python is fun'   # Single quotes
s3 = '''Multiline
String'''              # Triple quotes for multi-line strings

String Concatenation & Repetition

name = "Python"
print(name + " Rocks!")  # Concatenation
print(name * 3)          # Repetition
# Output:
Python Rocks!
PythonPythonPython

String Indexding & Slicing

Strings are indexed, starting from 0 (left to right) and -1 (right to left). Slicing extracts a portion of a string.

text = "Python"

print(text[0])     # Output: 'P'
print(text[-1])    # Output: 'n' (last character)
print(text[0:3])   # Output: 'Pyt' (slicing from index 0 to 2)

String Methods

Example Variables

s = "  Hello, Python!  "
s_alpha = "PythonRocks"
s_digit = "12345"
s_space = "   "
s_mixed = "Python123"
s_multiline = "Hello\nPython"
s_sentence = "hello, python is fun!"  # Added for capitalize() method

Case Conversion

# Case Conversion
print(s.lower())                # Convert to lowercase
print(s.upper())                # Convert to uppercase
print(s_sentence.capitalize())  # Capitalize the first character
print(s_sentence.title())       # Capitalize the first character of each word
print(s.swapcase())             # Swap the case of each character
# Output:
'  hello, python!  '
'  HELLO, PYTHON!  '
'Hello, python is fun!'
'Hello, Python Is Fun!'
'  hELLO, pYTHON!  '

Whitespace Management

# Whitespace Management
print(s.strip())          # Remove leading/trailing whitespace
print(s.lstrip())         # Remove leading whitespace
print(s.rstrip())         # Remove trailing whitespace
print(s_space.isspace())  # Check if string contains only whitespace
# Output:
'Hello, Python!'
'Hello, Python!  '
'  Hello, Python!'
True

Search & Replace

# Search and Replace
print(s.replace("Python", "World"))  # Replace substring
print(s.find("Python"))              # Find index of first occurrence (-1 if not found)
print(s.rfind("Python"))             # Find index of last occurrence
print(s.index("Python"))             # Find index of first occurrence (ValueError if not found)
print(s.rindex("Python"))            # Find index of last occurrence (ValueError if not found)
# Output:
'  Hello, World!  '
8
8
8
8

Split & Join

# Split and Join
print(s.split(","))                  # Split string by delimiter
print(s.splitlines())                # Split string into lines
print("-".join(s_alpha))             # Join characters with a delimiter
# Output:
['  Hello', ' Python!  ']
['  Hello, Python!  ']
'P-y-t-h-o-n-R-o-c-k-s'

Check String Properties

# Check String Properties
print(s_alpha.isalpha())            # Check if all characters are alphabetic
print(s_digit.isdigit())            # Check if all characters are digits
print(s_mixed.isalnum())            # Check if all characters are alphanumeric
print(s_alpha.islower())            # Check if all characters are lowercase
print(s_alpha.isupper())            # Check if all characters are uppercase
print(s_alpha.startswith("Py"))    # Check if string starts with a substring
print(s_alpha.endswith("Rocks"))   # Check if string ends with a substring
# Output:
True
True
True
False
False
True
True

String Alignment

# Alignment Methods
print(s.center(20, "-"))            # Center the string with padding
print(s.ljust(20, "*"))             # Left-align the string with padding
print(s.rjust(20, "."))             # Right-align the string with padding
# Output:
'---  Hello, Python!  ---'
'  Hello, Python!  ******'
'......  Hello, Python!  '

Encode & Decode

# Encode and Decode
encoded = s.encode("utf-8")          # Encode string to bytes
print(encoded)
print(encoded.decode("utf-8"))       # Decode bytes to string
# Output:
b'  Hello, Python!  '
'  Hello, Python!  '

Count Occurrences

# Count Occurrences
print(s.count("l"))                 # Count occurrences of a substring
# Output:
3

String Testing

# String Testing
print(s_multiline.isprintable())    # Check if all characters are printable
print(s_alpha.isidentifier())       # Check if valid Python identifier
# Output:
False
True

Booleans and NoneType

Boolean (bool)

Boolean values are True and False (capitalized in Python). Internally, True is 1, and False is 0.

a = True
b = False

print(a + 1)  # Output: 2 (True behaves as 1)
print(b * 5)  # Output: 0 (False behaves as 0)

NoneType (none)

None represents the absence of a value or a null value.

x = None
print(x)       # Output: None
print(type(x)) # Output: <class 'NoneType'>

Type Conversion & Casting

Implicit Type Conversion (Automatic)

Python automatically converts smaller data types to larger ones.

num_int = 5
num_float = 2.5

result = num_int + num_float  # int + float → float
print(result)       # Output: 7.5
print(type(result)) # Output: <class 'float'>

Explicit Type Conversion (Casting)

You can manually convert data types using built-in functions.

# Convert int to float
x = float(10)  
print(x)  # Output: 10.0

# Convert float to int (truncates decimal)
y = int(3.99)  
print(y)  # Output: 3

# Convert number to string
num = 123
str_num = str(num)
print(str_num)  # Output: '123'

# Convert string to int

str_val = "456"
int_val = int(str_val)
print(int_val)  # Output: 456