Variables — Exercises

Practice naming, assigning, swapping, scope and best practices.

1. Basic assignment

  1. Create variables name, age, city and print:
    Name: {name}, Age: {age}, City: {city}
  2. Assign a = 5, b = 10. Swap them so that a becomes 10 and b becomes 5 without using a temporary variable.

2. Multiple & chained assignment

  1. Use a single line to assign x = 1, y = 2, z = 3.
  2. What does a = b = c = 0 do? Write code and print the values.

3. Types & dynamic typing

  1. Show with code how a variable can change type (int → str → float).
  2. Predict output:
    x = "5"
    y = 2
    print(x + str(y))
    print(int(x) + y)

4. Scope

  1. Write a function that sets a variable msg inside it and try to print msg outside — explain the error.
  2. Use the global keyword to modify a global variable inside a function; show a short example and explain why globals are discouraged.

5. Best-practice tasks

  1. Rename poorly named variables (x1, a, b) to descriptive names in a given snippet.
  2. Write a short program that uses descriptive variables to calculate simple interest: I = P * R * T / 100. Print a nicely formatted sentence (use f-string).

← Back to Topics


Show answers — Variables worksheet

1. Basic assignment

# 1. Example solution
name = "Rekha"
age = 21
city = "Mumbai"
print(f"Name: {name}, Age: {age}, City: {city}")

# 2. Swap without temp variable
a = 5; b = 10
a, b = b, a
print(a, b)  # 10 5

2. Multiple & chained assignment

# 3. single-line multiple assignment
x, y, z = 1, 2, 3

# 4. chained assignment sets all variables to same value
a = b = c = 0
print(a, b, c)  # 0 0 0

3. Types & dynamic typing

# 5. variable changing types
x = 10        # int
x = "ten"     # str
x = 3.5       # float

# 6. predict output
x = "5"
y = 2
print(x + str(y))   # "52"
print(int(x) + y)   # 7

4. Scope

# 7. local variable scope example
def f():
    msg = "hello"
# print(msg)  -> NameError: msg is not defined

# 8. global keyword example (not recommended generally)
g = "outer"
def change():
    global g
    g = "changed"
change()
print(g)  # "changed"

5. Best-practice tasks

# 9. rename poor names (example)
width, height = 10, 5

# 10. simple interest
P = 10000
R = 5
T = 2
I = P * R * T / 100
print(f"Simple interest for P={P}, R={R}%, T={T}yrs is {I}")