Python Variables and Data Types

Python is a powerful and easy-to-learn programming language that’s perfect for beginners. This tutorial covers the fundamentals of variables and data types in Python, helping you build a strong foundation for your programming journey.

What are Variables?

Variables are containers for storing data values. In Python, you don’t need to declare the type of a variable - Python automatically determines the type based on the value you assign.

Creating Variables

# Variable assignment
name = "John"
age = 25
height = 5.9
is_student = True

# Printing variables
print(name)        # Outputs: John
print(age)         # Outputs: 25
print(height)      # Outputs: 5.9
print(is_student)  # Outputs: True

Basic Data Types

1. Strings (str)

Strings are sequences of characters enclosed in quotes.

# Single quotes
greeting = 'Hello'

# Double quotes
message = "Welcome to Python"

# Triple quotes for multi-line strings
long_text = """This is a
multi-line string
in Python"""

# String operations
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Outputs: John Doe

# String methods
text = "hello world"
print(text.upper())     # Outputs: HELLO WORLD
print(text.title())     # Outputs: Hello World
print(len(text))        # Outputs: 11

2. Numbers

Python supports different types of numbers:

Integers (int)

Whole numbers without decimal points.

count = 10
temperature = -5
big_number = 1000000

# Arithmetic operations
x = 10
y = 3
print(x + y)   # Outputs: 13
print(x - y)   # Outputs: 7
print(x * y)   # Outputs: 30
print(x / y)   # Outputs: 3.333...
print(x // y)  # Outputs: 3 (integer division)
print(x % y)   # Outputs: 1 (remainder)
print(x ** y)  # Outputs: 1000 (exponent)

Floats (float)

Numbers with decimal points.

price = 19.99
pi = 3.14159
temperature = 98.6

# Float operations
x = 3.5
y = 2.0
print(x + y)   # Outputs: 5.5
print(round(x, 1))  # Outputs: 3.5

3. Booleans (bool)

Represents truth values: True or False.

is_active = True
is_complete = False
has_permission = True

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

# Comparison operators
x = 10
y = 5
print(x > y)     # Outputs: True
print(x == y)    # Outputs: False
print(x != y)    # Outputs: True

4. Lists

Ordered collections of items.

# Creating lists
fruits = ["apple", "banana", "orange"]
numbers = [1, 2, 3, 4, 5]
mixed = ["hello", 42, True, 3.14]

# List operations
fruits.append("grape")        # Add item
fruits.insert(1, "kiwi")      # Insert at index
fruits.remove("banana")        # Remove item
popped = fruits.pop()         # Remove and return last item

# Accessing items
print(fruits[0])               # Outputs: apple
print(fruits[-1])              # Outputs: last item
print(fruits[1:3])             # Outputs: items at index 1 and 2

# List methods
print(len(fruits))             # Outputs: number of items
print("apple" in fruits)       # Outputs: True

5. Dictionaries

Key-value pairs for storing related data.

# Creating dictionaries
person = {
    "name": "John Doe",
    "age": 30,
    "city": "New York"
}

# Accessing values
print(person["name"])          # Outputs: John Doe
print(person.get("age"))       # Outputs: 30

# Adding and updating
person["email"] = "[email protected]"
person["age"] = 31

# Removing items
del person["city"]
email = person.pop("email")

# Dictionary methods
print(person.keys())           # Outputs: list of keys
print(person.values())         # Outputs: list of values
print(person.items())          # Outputs: list of key-value pairs

Type Conversion

You can convert between different data types:

# To string
text = str(123)        # "123"
text = str(3.14)       # "3.14"

# To integer
number = int("123")    # 123
number = int(3.9)      # 3 (truncates)

# To float
decimal = float("3.14")   # 3.14
decimal = float(123)      # 123.0

# To list
letters = list("hello")    # ['h', 'e', 'l', 'l', 'o']

Variable Naming Rules

  • Must start with a letter or underscore (_)
  • Can contain letters, numbers, and underscores
  • Case sensitive (name, Name, and NAME are different)
  • Cannot use Python keywords
# Good variable names
user_name = "John"
total_count = 42
is_valid = True

# Bad variable names (don't use)
2user = "John"      # Starts with number
user-name = "John"  # Contains hyphen
class = "Python"    # Uses Python keyword

Checking Variable Types

Use the type() function to check a variable’s type:

x = 10
y = "hello"
z = [1, 2, 3]

print(type(x))  # Outputs: <class 'int'>
print(type(y))  # Outputs: <class 'str'>
print(type(z))  # Outputs: <class 'list'>

# Check if variable is specific type
print(isinstance(x, int))     # Outputs: True
print(isinstance(y, str))     # Outputs: True
print(isinstance(z, list))    # Outputs: True

Best Practices

  1. Use descriptive names: user_age is better than x
  2. Follow naming conventions: Use snake_case for variables
  3. Initialize variables: Always give variables a value before using them
  4. Use constants: For values that don’t change, use ALL_CAPS
# Constants (convention)
PI = 3.14159
MAX_ATTEMPTS = 3
API_KEY = "your_api_key_here"

# Descriptive variable names
user_name = "Alice"
account_balance = 1250.75
is_authenticated = True

Summary

Data TypeDescriptionExample
strText data"Hello"
intWhole numbers42
floatDecimal numbers3.14
boolTrue/False valuesTrue
listOrdered collection[1, 2, 3]
dictKey-value pairs{"key": "value"}

External Resources:

Related Tutorials:

Last updated on