Python Basics — Variables & Data Types Exercises

2 minute read

Practice Exercises — Variables & Data Types

Test your understanding of variables, numbers, strings, booleans, None, and type conversion.


Exercise 1: Variable Swap

Given two variables, swap their values without using a temporary variable. Print the values before and after.

x = 100
y = 200
# Swap x and y, then print both
Show Answer

Answer:

x = 100
y = 200

print(f"Before: x = {x}, y = {y}")

x, y = y, x

print(f"After: x = {x}, y = {y}")

Expected output:

Before: x = 100, y = 200
After: x = 200, y = 100

Explanation: Python’s tuple unpacking (x, y = y, x) evaluates the right side first, then assigns both values simultaneously.


Exercise 2: Type Detective

Predict the type and value of each expression without running the code. Then verify your answers.

a = 10 / 3
b = 10 // 3
c = 10 % 3
d = True + True + False
e = bool("")
Show Answer

Answer:

a = 10 / 3
print(f"a = {a}, type = {type(a).__name__}")
# a = 3.3333333333333335, type = float

b = 10 // 3
print(f"b = {b}, type = {type(b).__name__}")
# b = 3, type = int

c = 10 % 3
print(f"c = {c}, type = {type(c).__name__}")
# c = 1, type = int

d = True + True + False
print(f"d = {d}, type = {type(d).__name__}")
# d = 2, type = int (True=1, False=0: 1+1+0=2)

e = bool("")
print(f"e = {e}, type = {type(e).__name__}")
# e = False, type = bool (empty string is falsy)

Exercise 3: Temperature Converter

Write a program that converts a temperature from Fahrenheit to Celsius. The formula is:

\[C = \frac{5}{9} \times (F - 32)\]

Convert 98.6°F (body temperature) and print the result rounded to 1 decimal place.

Show Answer

Answer:

fahrenheit = 98.6
celsius = (5 / 9) * (fahrenheit - 32)
print(f"{fahrenheit}°F = {celsius:.1f}°C")

Expected output:

98.6°F = 37.0°C

Key concepts: Float arithmetic, f-string formatting with :.1f for one decimal place.


Exercise 4: String Manipulation

Given the string below, extract and print:

  1. The first character
  2. The last character
  3. The string reversed
  4. The length of the string
text = "Python Basics"
Show Answer

Answer:

text = "Python Basics"

print(f"First character: {text[0]}")
print(f"Last character: {text[-1]}")
print(f"Reversed: {text[::-1]}")
print(f"Length: {len(text)}")

Expected output:

First character: P
Last character: s
Reversed: scisaB nohtyP
Length: 13

Key concepts: Zero-based indexing, negative indexing (-1), slice with step ([::-1]), len().


Exercise 5: Safe Type Conversion

Write a function called safe_int() that takes a string and returns the integer value if conversion is possible, or None if it fails. Test it with these inputs: "42", "3.14", and "hello".

Show Answer

Answer:

def safe_int(value):
    """Safely convert a string to int, returning None on failure."""
    try:
        return int(value)
    except ValueError:
        try:
            return int(float(value))  # Handle "3.14" → 3
        except ValueError:
            return None

# Test cases
print(safe_int("42"))      # 42
print(safe_int("3.14"))    # 3
print(safe_int("hello"))   # None

# Verify types
result = safe_int("hello")
print(result is None)      # True

Expected output:

42
3
None
True

Key concepts: try/except for error handling, int() truncation, is None check, two-stage conversion for float strings.


Scoring Guide

Score Level
5/5 Excellent — Variables and data types mastered
4/5 Great — Solid understanding, review what you missed
3/5 Good — Review type conversion and string operations
2/5 Needs Work — Re-read the variables and data types chapter
1/5 Keep Going — Focus on basics: variables, types, and type()

Next chapter: Operators →

Updated: