Practice: Python Variables
Q1. Store and print your name
Create a variable called name that holds the text Maya and print it.
Goal: Understand variables and assignment.
Q2. Add two variables
Create variables a = 12 and b = 30 and print their sum.
Goal: Understand variables and assignment.
Q3. Swap two values
Set x = 1 and y = 2, swap them in a single line without a helper variable, then print x and y on one line.
Goal: Swap variables.
Q4. Update a counter
Start with count = 0. Add 1 three times using +=, then print count.
Goal: Reassign variables.
Q5. Rectangle area
Use variables length = 8 and width = 5 to calculate the area and print Area: followed by the result.
Goal: Understand variables and assignment.
Q6. Unpack three values
Unpack the tuple (3, 4, 5) into names a, b and c in one line, then print c, b, a on one line.
Goal: Use unpacking.
Q7. Collect the rest
From the list [1, 2, 3, 4, 5] get the first item in first and all other items in rest using one assignment. Print first, then rest.
Goal: Use unpacking.
Q8. Same value for many names
Give the names p, q and r the same value 7 in one line and print p + q + r.
Goal: Use multiple assignment.
Q9. Simple reassignment
What does this print?
n = 4
n = n * 2
n = n + 1
print(n)Goal: Trace reassignment.
Q10. Names are case sensitive
What does this print?
total = 5
Total = 10
print(total + Total)Goal: Know case sensitivity.
Q11. Copy of a name
What does this print?
a = 3
b = a
a = 8
print(a, b)Goal: Names point to values.
Q12. Swap trace
What does this print?
a, b = 2, 5
a, b = b, a + b
print(a, b)Goal: Understand swapping.
Q13. Chained assignment
What does this print?
x = y = 10
x += 5
print(x, y)Goal: Names point to values.
Q14. Identity of names
What does this print?
a = 1000
b = a
print(a is b)
b = b + 0
print(a == b)Goal: Use is and == correctly.
Q15. Star unpacking in the middle
What does this print?
a, *b, c = [1, 2, 3, 4, 5]
print(a, b, c)Goal: Use unpacking.
Q16. Fix the invalid name
This code has a bug. Fix it so it prints 10.
2nd_value = 10
print(2nd_value)Goal: Follow naming rules.
Q17. Fix the case mistake
This code raises NameError. Fix it so it prints 6.
price = 6
print(Price)Goal: Spot NameError.
Q18. Fix the keyword name
This code is invalid. Fix it so it prints 3.
class = 3
print(class)Goal: Avoid keywords.
Q19. Fix the hidden built-in
After this code, calling sum on a list fails. Rename the variable so that the program prints 6.
sum = 0
for n in [1, 2, 3]:
sum += n
print(sum)Goal: Avoid shadowing built-ins.
Q20. What is a variable?
In one or two sentences, explain what the statement score = 10 does in Python.
Goal: Define a variable.