Variables & Data Types
Learn how Python handles variables, explore the fundamental data types, and understand type casting and introspection.
Numbers
Python supports several numeric types including integers, floating-point numbers, and complex numbers. Integers in Python have arbitrary precision, meaning they can be as large as your memory allows. Floating-point numbers follow the IEEE 754 standard and have the usual precision limitations. Python also provides built-in functions for mathematical operations and the math module for more advanced calculations.
# Integer operations
x = 42
y = -17
print(x + y) # 25
print(x ** 2) # 1764 (exponentiation)
print(x // y) # -3 (floor division)
print(x % y) # -9 (modulo)
# Floating-point numbers
pi = 3.14159
e = 2.71828
print(round(pi, 2)) # 3.14
# Complex numbers
z = 3 + 4j
print(z.real) # 3.0
print(z.imag) # 4.0
print(abs(z)) # 5.0
Strings
Strings in Python are immutable sequences of Unicode characters. They can be defined using single quotes, double quotes, or triple quotes for multi-line strings. Python provides a rich set of string methods for manipulation, searching, and formatting. F-strings, introduced in Python 3.6, offer the most readable and efficient way to embed expressions inside string literals.
# String creation and methods
greeting = "Hello, World!"
print(greeting.lower()) # "hello, world!"
print(greeting.split(", ")) # ['Hello', 'World!']
print(greeting.replace("World", "Python")) # "Hello, Python!"
# String slicing
text = "Python Programming"
print(text[0:6]) # "Python"
print(text[-11:]) # "Programming"
print(text[::-1]) # "gnimmargorP nohtyP"
# Multi-line strings
poem = """Roses are red,
Violets are blue,
Python is awesome,
And so are you."""
print(poem)
Booleans and None
Booleans in Python are represented by the True and False keywords and are a subclass of integers. Python uses truthy and falsy values extensively, where empty containers, zero, None, and empty strings evaluate to False. The None type represents the absence of a value and is commonly used as a default argument or return value. Understanding truthiness is crucial for writing idiomatic Python code.
# Boolean values and operations
is_active = True
is_deleted = False
print(is_active and not is_deleted) # True
# Truthy and falsy values
print(bool(0)) # False
print(bool("")) # False
print(bool([])) # False
print(bool(None)) # False
print(bool(42)) # True
print(bool("hello")) # True
# None type
result = None
if result is None:
print("No result yet")
# Identity vs equality
a = None
print(a is None) # True (preferred)
print(a == None) # True (not recommended)
Type Introspection and Casting
Python is dynamically typed, meaning variables can change type during execution. The type() function reveals the type of any object, while isinstance() checks if an object is an instance of a specific class. Type casting allows you to convert between types using built-in functions like int(), float(), str(), and bool(). Understanding these functions is essential for handling user input and data processing.
# Checking types
x = 42
print(type(x)) # <class 'int'>
print(isinstance(x, int)) # True
# Type casting
num_str = "123"
num_int = int(num_str)
print(num_int + 1) # 124
price = float("19.99")
print(price * 2) # 39.98
# Converting to string
count = 42
message = "Items: " + str(count)
print(message) # "Items: 42"
# Casting edge cases
print(int(3.9)) # 3 (truncates, does not round)
print(bool(1)) # True
print(list("hello")) # ['h', 'e', 'l', 'l', 'o']