Practice: Python Data Types
Q1. Print the type of a value
Print the type of the value 3.5.
Goal: Use type().
Q2. Convert text to number and add
Given s = "40", convert it to an int, add 2 and print the result.
Goal: Convert str to int.
Q3. Remove duplicates
From data = [4, 2, 4, 1, 2], print the sorted unique values as a list.
Goal: Use a set for uniqueness.
Q4. Dictionary lookup
Create a dict with keys name and age for a person (Mia, 30). Print the age.
Goal: Use a dict.
Q5. Check with isinstance
Print True if the value 10 is an int, using isinstance.
Goal: Use isinstance().
Q6. Single-item tuple
Create a tuple with the single item 9 and print its type and its length.
Goal: Create a one-item tuple.
Q7. Count types in a list
Given items = [1, "a", 2.5, 3, "b"], print how many are strings.
Goal: Filter values by type.
Q8. Safe bool of text
Print the Boolean value of an empty string and of the string 0.
Goal: Understand truthiness.
Q9. Type of a division
What does this print?
print(type(10 / 2))Goal: Know division types.
Q10. Floor division type
What does this print?
print(10 // 2)
print(type(10 // 2))Goal: Know floor division.
Q11. Shared list
What does this print?
a = [1, 2]
b = a
b.append(3)
print(a)Goal: Understand mutability.
Q12. Tuple concatenation
What does this print?
x = (1, 2)
y = x + (3,)
print(x)
print(y)Goal: Understand immutability.
Q13. Bool as number
What does this print?
print(True + True)
print(isinstance(True, int))Goal: Know bool is an int.
Q14. Empty braces
What does this print?
a = {}
b = set()
print(type(a))
print(type(b))Goal: Remember the empty-set rule.
Q15. Truthiness of values
What does this print?
print(bool(0), bool(1), bool([]), bool([0]), bool(None))Goal: Understand truthiness.
Q16. Fix the TypeError
This program should print 15 but raises a TypeError. Fix it.
total = "10" + 5
print(total)Goal: Fix a type mismatch.
Q17. Fix the item assignment
This code tries to change the first letter of a string and fails. Make word become Cat.
word = "cat"
word[0] = "C"
print(word)Goal: Work with immutable strings.
Q18. Fix the empty set
The code should print an empty set's length 0 and add item 5, giving 1. Currently it fails. Fix it.
s = {}
s.add(5)
print(len(s))Goal: Fix the empty-set trap.
Q19. Mutable or immutable?
List the built-in types list, str, tuple, dict, int and set under the headings mutable and immutable.
Goal: Classify types.
Q20. Choose a data type
Which type would you use to store the days of a week that never change? Which for a shopping list that changes? Explain briefly.
Goal: Choose a suitable type.