Variables and Data Types

Daniel Sarney
Python For Beginners

Now that you've written your first Python program and understand the basics of running code, it's time to learn about one of the most fundamental concepts in programming: variables and data types. These are the building blocks that allow you to store information, manipulate data, and build more complex programs.

Think of variables as labeled containers that hold information. Just like you might label a box "books" or "tools," variables give names to pieces of data so you can use them later in your program. Understanding how to work with different types of data—text, numbers, and true/false values—is essential for writing useful Python programs.

In this lesson, you'll learn how to create variables, understand Python's different data types, and see how to work with each type effectively. By the end, you'll be able to store information, perform calculations, and manipulate text in your programs.

What You'll Learn

  • How to create and use variables in Python
  • Understanding Python's basic data types: strings, integers, floats, and booleans
  • How to convert between different data types
  • Working with string operations and formatting
  • Performing mathematical operations with numbers
  • Best practices for naming variables

Understanding Variables

A variable is a name that refers to a value stored in your computer's memory. In Python, creating a variable is incredibly simple—you just assign a value to a name using the equals sign (=). Python automatically figures out what type of data you're storing.

Here's your first example of creating variables:

# Creating variables is as simple as assigning a value
name = "Daniel"
age = 30
height = 5.11
is_student = True

# Now we can use these variables
print(name)
print(age)
print(height)
print(is_student)

In this example, we've created four variables:

  • name stores text (a string)
  • age stores a whole number (an integer)
  • height stores a decimal number (a float)
  • is_student stores a true/false value (a boolean)

Notice how Python automatically determines the data type based on the value you assign. You don't need to tell Python "this is a string" or "this is a number"—it figures it out for you!

Python's Basic Data Types

Python has several built-in data types. Let's explore the four most fundamental ones that you'll use constantly:

Strings: Working with Text

Strings are sequences of characters enclosed in quotation marks. You can use either single quotes (') or double quotes ("), but they must match. Strings are perfect for storing names, messages, addresses, or any text data.

# Different ways to create strings
first_name = "Daniel"
last_name = 'Sarney'
message = "Welcome to Python programming!"
quote = 'He said, "Python is awesome!"'

# You can combine strings using the + operator
full_name = first_name + " " + last_name
print(full_name)  # Output: Daniel Sarney

# Strings can be multiplied (repeated)
excited = "Python! " * 3
print(excited)  # Output: Python! Python! Python!

Strings have many useful operations. You can find their length, convert them to uppercase or lowercase, and access individual characters. Here's a practical example:

# String operations
course = "Python for Beginners"
print(len(course))  # Output: 20 (number of characters)
print(course.upper())  # Output: PYTHON FOR BEGINNERS
print(course.lower())  # Output: python for beginners
print(course.replace("Beginners", "Experts"))  # Output: Python for Experts

Integers: Whole Numbers

Integers are whole numbers without decimal points. You can use them for counting, indexing, and mathematical calculations. Python can handle very large integers, so you don't need to worry about size limits for most practical purposes.

# Creating integer variables
count = 42
temperature = -10
year = 2025
population = 8000000000

# Mathematical operations with integers
a = 10
b = 3
print(a + b)  # Addition: 13
print(a - b)  # Subtraction: 7
print(a * b)  # Multiplication: 30
print(a // b)  # Integer division: 3 (whole number result)
print(a % b)  # Modulo (remainder): 1
print(a ** b)  # Exponentiation (power): 1000

Notice the difference between regular division (/) and integer division (//). Regular division always returns a float, while integer division returns an integer by dropping the decimal part.

Floats: Decimal Numbers

Floats represent real numbers with decimal points. They're used for measurements, calculations requiring precision, and any situation where you need fractional values.

# Creating float variables
price = 19.99
temperature = 98.6
pi = 3.14159
percentage = 0.85

# Mathematical operations work the same way
x = 10.5
y = 3.2
print(x + y)  # Output: 13.7
print(x * y)  # Output: 33.6
print(x / y)  # Output: 3.28125

# Be aware of floating-point precision
result = 0.1 + 0.2
print(result)  # Output: 0.30000000000000004 (tiny rounding error)

Floating-point numbers can sometimes have tiny rounding errors due to how computers represent decimal numbers. This is normal and usually doesn't cause problems, but it's good to be aware of it.

Booleans: True or False

Booleans represent truth values—either True or False. They're essential for making decisions in your programs (which we'll cover in later lessons). Boolean values are often the result of comparisons.

# Creating boolean variables
is_python_fun = True
is_raining = False
has_experience = True

# Booleans from comparisons
age = 25
is_adult = age >= 18
print(is_adult)  # Output: True

temperature = 72
is_hot = temperature > 80
print(is_hot)  # Output: False

# Boolean operations
print(True and False)  # Output: False
print(True or False)  # Output: True
print(not True)  # Output: False

Type Conversion

Sometimes you need to convert data from one type to another. Python provides built-in functions for this: str(), int(), float(), and bool(). This is called type casting or type conversion.

# Converting between types
age = 25
age_string = str(age)  # Convert integer to string
print("I am " + age_string + " years old")

# Converting string to number
price_string = "19.99"
price = float(price_string)
total = price * 2
print(total)  # Output: 39.98

# Converting to integer (truncates decimal)
height = 5.11
height_int = int(height)
print(height_int)  # Output: 5

# Converting to boolean
print(bool(1))  # Output: True
print(bool(0))  # Output: False
print(bool(""))  # Output: False (empty string)
print(bool("Hello"))  # Output: True (non-empty string)

Variable Naming Best Practices

Python has rules and conventions for naming variables. Following these makes your code more readable and professional:

Rules (must follow):

  • Variable names can only contain letters, numbers, and underscores
  • They cannot start with a number
  • They cannot be Python keywords (like if, for, print)

Conventions (should follow):

  • Use descriptive names that explain what the variable stores
  • Use lowercase letters with underscores for multiple words (snake_case)
  • Avoid single letters except for temporary variables
# Good variable names
user_name = "Daniel"
total_price = 99.99
is_logged_in = True
number_of_items = 42

# Bad variable names (avoid these)
x = "Daniel"  # Not descriptive
totalPrice = 99.99  # Use snake_case, not camelCase
2name = "Daniel"  # Can't start with number
if = 5  # Can't use Python keywords

Working with Multiple Variables

Real programs use many variables together. Here's a practical example that combines everything we've learned:

# A simple program that calculates total cost
item_name = "Python Course"
item_price = 49.99
quantity = 2
tax_rate = 0.08  # 8% tax

# Calculate subtotal
subtotal = item_price * quantity

# Calculate tax
tax_amount = subtotal * tax_rate

# Calculate total
total = subtotal + tax_amount

# Display results
print("Item: " + item_name)
print("Quantity: " + str(quantity))
print("Subtotal: £" + str(subtotal))
print("Tax: £" + str(tax_amount))
print("Total: £" + str(total))

This example shows how variables work together to solve a real problem. Each variable stores a piece of information, and we combine them using mathematical operations to get our final result.

Try It Yourself

Practice what you've learned with these exercises:

  1. Create a personal information program: Create variables for your name (string), age (integer), height in feet (float), and whether you're a student (boolean). Print all of them with descriptive labels.

  2. String manipulation: Create a variable with your full name, then:
    a. Print it in uppercase
    b. Print it in lowercase
    c. Print its length
    d. Create a new variable that combines your first and last name with a space

  3. Calculator practice: Create two number variables and perform all basic operations (addition, subtraction, multiplication, division). Print each result with a label explaining what operation was performed.

  4. Type conversion challenge: Create a string variable containing a number (like "42"), convert it to an integer, multiply it by 2, convert the result back to a string, and print it with a message.

These exercises will help you become comfortable with variables and data types, which are essential for everything else you'll learn in Python.

Summary

In this lesson, you've learned the fundamentals of working with data in Python. You now understand how to create variables to store information, and you're familiar with Python's four basic data types: strings for text, integers for whole numbers, floats for decimal numbers, and booleans for true/false values.

You've seen how to perform operations on each data type, convert between types when needed, and follow best practices for naming variables. Most importantly, you've learned that variables are the foundation that allows you to store and manipulate information in your programs.

Remember, variables are like labeled boxes—they give names to your data so you can use it throughout your program. The more you practice creating and using variables, the more natural it will become.

What's Next?

In the next lesson, we'll explore how to get input from users and display formatted output. You'll learn how to make your programs interactive by asking users for information, and you'll discover powerful ways to format strings that make your output look professional. This will allow you to create programs that can respond to different inputs and produce customized results.

Video Tutorial Coming Soon

The video tutorial for this lesson will be available soon. Check back later!

Continue Learning

18 lessons
Python Intermediate

Start your learning journey with Python Intermediate. This course includes comprehensive lessons covering everything you need to know.