Variables — Exercises
Practice naming, assigning, swapping, scope and best practices.
1. Basic assignment
- Create variables
name,age,cityand print:Name: {name}, Age: {age}, City: {city} - Assign
a = 5,b = 10. Swap them so thatabecomes 10 andbbecomes 5 without using a temporary variable.
2. Multiple & chained assignment
- Use a single line to assign
x = 1,y = 2,z = 3. - What does
a = b = c = 0do? Write code and print the values.
3. Types & dynamic typing
- Show with code how a variable can change type (int → str → float).
- Predict output:
x = "5" y = 2 print(x + str(y)) print(int(x) + y)
4. Scope
- Write a function that sets a variable
msginside it and try to printmsgoutside — explain the error. - Use the
globalkeyword to modify a global variable inside a function; show a short example and explain why globals are discouraged.
5. Best-practice tasks
- Rename poorly named variables (
x1, a, b) to descriptive names in a given snippet. - 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).
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}")