Variables and Data Types

Chapter 1: Variables and Data Types

Understanding Data Types

Every value in Python has a type. Types determine what operations you can perform and how Python stores the data internally. Understanding types is fundamental to writing correct programs—you can't add a number to text, but you can add two numbers or join two pieces of text.

Python has several built-in data types, but we'll focus on the three you'll use constantly: strings (text), numbers (integers and floats), and booleans (True/False). These core types handle the vast majority of programming tasks. Master these, and you'll have a solid foundation for everything else.

Python determines types automatically when you create values. You don't need to declare "this variable holds a number"—Python figures it out from context. This automatic typing makes Python feel natural, but you still need to understand what types your data has, especially when errors occur.

Why do types matter? They prevent mistakes. Trying to multiply text by text doesn't make sense, so Python catches that error. Types also optimize performance—Python stores integers differently than floats, using the most efficient representation for each. When you understand types, you understand how your data behaves and can prevent bugs before they happen. You'll write clearer code because you'll think about what kinds of values your variables hold.

Strings: Working with Text

Strings represent text—any sequence of characters. Create strings by wrapping text in quotes (single or double). Strings are everywhere: user input, file contents, messages, labels, and more. They're one of the most frequently used types in Python programming.

Single and double quotes work identically—choose whichever makes your code clearer. If your string contains an apostrophe, double quotes avoid escaping: message = "She's here". If it contains double quotes, use single quotes: quote = 'He said "hello"'. For strings with both, use triple quotes or escape characters with backslashes.

Strings support many useful operations. Concatenation joins strings together using the + operator:

Strings have a length—the number of characters they contain. Use the len() function to find it:

You can repeat strings with the * operator, creating copies:

laugh = "Ha" * 3
print(laugh)  # Output: HaHaHa

Strings are immutable—once created, they can't be changed. When you "modify" a string, Python creates a new string:

original = "Hello"
modified = original + " there"  # Creates new string
# original is still "Hello"

String methods provide powerful text manipulation. The upper() method converts to uppercase, lower() to lowercase:

text = "Python Programming"
print(text.upper())  # Output: PYTHON PROGRAMMING
print(text.lower())  # Output: python programming

The replace() method substitutes text:

message = "I love Java"
fixed = message.replace("Java", "Python")
print(fixed)  # Output: I love Python

Numbers: Integers and Floats

Python has two main numeric types: integers (whole numbers) and floats (decimal numbers). Integers represent counts, positions, and exact values. Floats represent measurements, percentages, and approximate values.

age = 25          # Integer
price = 19.99     # Float
temperature = -5  # Integer (can be negative)
pi = 3.14159      # Float

The distinction between integers and floats matters more than you might think. Integers are precise—exactly 5 means 5, with no rounding or approximation. Floats can have tiny rounding errors due to binary representation. For counting things (5 apples, 10 users, 100 iterations), use integers. For measurements and calculations where exact precision isn't critical (2.5 meters, 98.6 degrees, 3.14 radians), use floats. When you divide numbers, Python gives you a float even if the division is exact. This ensures you don't lose precision—10 / 2 gives 5.0, not 5.

Standard arithmetic operations work as expected:

# Addition and subtraction
total = 10 + 5    # 15
difference = 10 - 3  # 7

# Multiplication and division
product = 4 * 5   # 20
quotient = 15 / 3  # 5.0 (always returns float)

# Integer division (discards remainder)
int_div = 17 // 5  # 3

# Modulo (remainder after division)
remainder = 17 % 5  # 2

# Exponentiation (power)
squared = 5 ** 2  # 25

# Print all results
print(f"Total: {total}")
print(f"Difference: {difference}")
print(f"Product: {product}")
print(f"Quotient: {quotient}")
print(f"Integer division: {int_div}")
print(f"Remainder: {remainder}")
print(f"Squared: {squared}")

Notice that regular division (/) always produces a float, even when dividing evenly. If you need an integer result, use integer division (//).

Python handles very large and very small numbers naturally:

big = 99999999999999999999
small = 0.0000000001
result = big + 1  # Works fine

You can mix integers and floats in calculations. Python automatically converts integers to floats when needed:

mixed = 10 + 5.5  # Result: 15.5 (float)

When working with money or precise decimals, be aware that floats can have tiny rounding errors due to how computers store decimals. For most purposes, this doesn't matter:

price = 0.1 + 0.2  # Actually 0.30000000000000004
# For display: round(price, 2) gives 0.3

Booleans: True and False

Booleans represent truth values—either True or False (note the capital letters). They're essential for making decisions and controlling program flow. You'll use booleans constantly in if-statements and loops.

is_valid = True
has_error = False
is_empty = False

Comparison operators create boolean values by comparing other values:

age = 25
is_adult = age >= 18  # True
is_senior = age >= 65  # False

temperature = 72
is_hot = temperature > 80  # False
is_comfortable = temperature == 72  # True

# Print the results
print(f"Age: {age}")
print(f"Is adult? {is_adult}")
print(f"Is senior? {is_senior}")
print(f"Temperature: {temperature}")
print(f"Is hot? {is_hot}")
print(f"Is comfortable? {is_comfortable}")

Comparison operators include:

  • == equal to (note the double equals)
  • != not equal to
  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

Be careful not to confuse = (assignment) with == (comparison). Assignment stores a value; comparison tests equality.

Logical operators combine boolean values:

age = 25
has_license = True

# AND: both must be True
can_drive = age >= 16 and has_license  # True

# OR: at least one must be True
can_enter = age >= 18 or has_license  # True

# NOT: reverses the boolean
is_minor = not (age >= 18)  # False

Some values are "truthy" or "falsy"—Python treats them as True or False in boolean contexts. Empty strings, zero, and None are falsy. Non-empty strings and non-zero numbers are truthy:

bool("")      # False (empty string)
bool("text")  # True (non-empty string)
bool(0)       # False
bool(42)      # True

Type Conversion

Sometimes you need to convert between types. Python provides conversion functions: str(), int(), float(), and bool().

Converting to strings with str() works for any value:

age = 25
age_text = str(age)  # "25"
message = "I am " + str(age) + " years old"

Converting to integers with int() works for strings containing whole numbers and for floats (discards decimal part):

text_number = "42"
number = int(text_number)  # 42

decimal = 3.7
whole = int(decimal)  # 3 (truncates, doesn't round)

Be careful—converting invalid strings to integers causes errors:

# int("hello")  # ValueError: invalid literal
# int("3.14")   # ValueError: invalid literal

Converting to floats with float() works for numeric strings:

text_price = "19.99"
price = float(text_price)  # 19.99

whole = 5
decimal = float(whole)  # 5.0

Converting to boolean with bool() follows the truthy/falsy rules:

bool(1)      # True
bool(0)      # False
bool("")     # False
bool("hi")   # True

You can check a value's type using the type() function:

print(type(42))          # <class 'int'>
print(type(3.14))        # <class 'float'>
print(type("hello"))     # <class 'str'>
print(type(True))        # <class 'bool'>

Practice Exercises

Apply what you've learned with these exercises:

Exercise 1: String Manipulation
Create a variable with your full name. Use string methods to print it in all uppercase, all lowercase, and calculate its length.

Exercise 2: Temperature Converter
Create a variable fahrenheit with value 98.6. Convert it to Celsius using the formula: celsius = (fahrenheit - 32) * 5 / 9. Print both values with descriptive messages.

Exercise 3: Shopping Cart
Create variables for three item prices (use floats). Calculate the total, then calculate a 20% discount. Print the original total and discounted total.

Exercise 4: Age Verification
Create variables age = 16 and has_permission = True. Use boolean logic to determine if someone can proceed (they need to be 18 or older, OR be under 18 with permission). Store the result in a variable and print it.

Exercise 5: Type Exploration
Create three variables: a string containing a number ("123"), an integer (456), and a float (7.89). Use type() to print the type of each. Then convert the string to an integer, and the integer to a float, printing the results and their types.

Exercise 6: String Building
Create variables for a product name, quantity (integer), and unit price (float). Build a formatted message like "5 apples at $1.25 each = $6.25" using string concatenation and the str() function.

Take time to experiment with variations. Try different values, different operations, and intentionally create errors to learn from the messages.

Next Steps

You now understand Python's fundamental data types: strings for text, numbers (integers and floats) for calculations, and booleans for logic. You know how to convert between types and perform common operations on each type.

Next, we'll explore control flow—how to make decisions with if-statements and repeat actions with loops. These structures, combined with your data type knowledge, enable you to write programs that respond to different conditions and process collections of data.

Continue to Chapter 2: Control Flow.

📝 Test Your Knowledge: Variables and Data Types

Take this quiz to reinforce what you've learned in this chapter.