CodeSparks Logo

CodeSparks

PYTHON

04
CHAPTER
ACTIVE

Variables and Data Types

Variables are fundamental building blocks in programming that allow us to store and manipulate data. Think of them as labeled containers where you can put different types of information and retrieve them whenever needed. This lesson will teach you how to create variables, follow naming conventions, and work with different data types in Python.

What are Variables?

DEFINITION
Variable
A named storage location in computer memory that holds data. Variables allow you to store values, reference them by name, and modify them throughout your program execution.

Variables are like labeled boxes in a warehouse. Each box (variable) has a name written on it, and you can put different items (data) inside. When you need something specific, you just look for the box with the right label. In programming, variables let you store numbers, text, lists, and other types of data.

FUN FACT

Python is dynamically typed, which means you do not need to declare what type of data a variable will hold. Python automatically figures it out based on the value you assign!

Creating Variables

Creating variables in Python is straightforward - you simply choose a name and assign a value using the equals sign (=). Python will automatically determine the data type based on the value you provide.

PYTHON
# Creating different types of variables
name = "Alice"
age = 25
height = 5.6
is_student = True
favorite_colors = ["blue", "green", "purple"]

# Using variables in output
print("Name:", name)
print("Age:", age)
print("Height:", height, "feet")
print("Is student:", is_student)
print("Favorite colors:", favorite_colors)

# Variables can be updated
age = 26
print("Updated age:", age)

Notice how we can store different types of data in variables - text (strings), whole numbers (integers), decimal numbers (floats), true/false values (booleans), and even collections of items (lists). Python handles all the complexity behind the scenes.

Variable Naming Rules

Python has specific rules for naming variables that you must follow, plus some best practices that will make your code more readable and maintainable.

DEFINITION
Snake Case
A naming convention where words are separated by underscores and written in lowercase, such as first_name, student_age, or total_score. This is the preferred naming style for variables in Python.

Required Rules (Your code will not work if you break these):

  • Must start with a letter (a-z, A-Z) or underscore (_)
  • Can contain letters, numbers, and underscores only
  • Cannot contain spaces or special characters (!@#$%^&*)
  • Cannot be a Python keyword (like if, for, while, def, etc.)
  • Are case-sensitive (name, Name, and NAME are different variables)

Best Practices (Follow these for clean, readable code):

  • Use descriptive names that explain what the variable holds
  • Use lowercase letters with underscores for multi-word names (snake_case)
  • Avoid abbreviations unless they are widely understood
  • Make names meaningful but not excessively long
  • Be consistent with your naming style throughout your code
PYTHON
# Good variable names
first_name = "John"
student_age = 20
total_score = 95.5
is_homework_complete = True

# Poor variable names (avoid these)
n = "John"           # Too short, unclear
studentAge = 20      # camelCase (not Python style)
ts = 95.5           # Abbreviation, unclear
x = True            # Meaningless name

Common Data Types

Python supports several built-in data types that cover most programming needs. Understanding these types will help you choose the right tool for storing different kinds of information.

DEFINITION
Data Type
A classification that specifies what kind of value a variable can hold and what operations can be performed on it. Examples include strings for text, integers for whole numbers, and booleans for true/false values.

Strings (Text Data):

Strings represent text and are enclosed in either single or double quotes. You can perform various operations on strings like combining them, finding their length, or formatting them with variables.

PYTHON
# Different ways to create strings
message = "Hello, World!"
name = 'Alice'
quote = "She said, 'Python is awesome!'"

# String operations
full_name = "John" + " " + "Doe"        # Concatenation
greeting = f"Hello, {name}!"            # f-string formatting
length = len(message)                   # Get string length
uppercase = message.upper()             # Convert to uppercase

print(full_name)    # Output: John Doe
print(greeting)     # Output: Hello, Alice!
print(length)       # Output: 13
print(uppercase)    # Output: HELLO, WORLD!

Numbers (Integers and Floats):

Python distinguishes between integers (whole numbers) and floats (decimal numbers). You can perform mathematical operations on both types, and Python will handle the calculations automatically.

PYTHON
# Integers (whole numbers)
age = 25
year = 2024
score = 100

# Floats (decimal numbers)
height = 5.9
price = 19.99
temperature = -2.5

# Mathematical operations
addition = 10 + 5           # Result: 15
subtraction = 10 - 3        # Result: 7
multiplication = 4 * 6      # Result: 24
division = 15 / 3           # Result: 5.0 (always returns float)
floor_division = 17 // 5    # Result: 3 (integer division)
exponentiation = 2 ** 3     # Result: 8
modulo = 17 % 5            # Result: 2 (remainder)

print(f"Addition: {addition}")
print(f"Division: {division}")
print(f"Floor division: {floor_division}")
print(f"Modulo: {modulo}")

Booleans (True/False Values):

Booleans represent truth values and are essential for making decisions in your programs. They can only be True or False (note the capitalization).

PYTHON
# Boolean variables
is_sunny = True
is_raining = False
has_homework = True

# Booleans from comparisons
is_adult = age >= 18
is_passing_grade = score >= 70
is_weekend = day == "Saturday" or day == "Sunday"

print(f"Is adult: {is_adult}")
print(f"Is passing: {is_passing_grade}")

# Using booleans in conditions
if is_sunny:
    print("Great day for a walk!")
if not is_raining:
    print("No need for an umbrella!")
FUN FACT

Python's f-string formatting (the f before the quotes) was introduced in Python 3.6 and is now the preferred way to format strings. It is faster and more readable than older formatting methods!

Understanding variables and data types is crucial for all future Python programming. These concepts form the foundation upon which you will build more complex programs. Practice creating variables with different data types and experimenting with operations to solidify your understanding.