Day 25 — Python Tricks (Practice Problems)

Here are some hands-on problems to strengthen your understanding of Python Tricks. Try solving them before looking at solutions.

1. Swap Without Temp

Swap two variables in a single line without using a third variable.

a = 15
b = 25
# Your code here
print(a, b)  # Expected: 25 15
        

2. Squares with List Comprehension

Generate a list of squares of numbers from 1 to 10 using list comprehension.

# Your code here
# Expected: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
        

3. Dictionary Comprehension

Create a dictionary with numbers from 1–5 as keys and their cubes as values.

# Your code here
# Expected: {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}
        

4. Zip Two Lists

Combine two lists of names and scores and print them using zip().

names = ["Alice", "Bob", "Charlie"]
scores = [90, 80, 85]
# Your code here
# Expected Output:
# Alice 90
# Bob 80
# Charlie 85
        

5. Enumerate with Index

Use enumerate() to print items with their positions.

fruits = ["Apple", "Banana", "Cherry"]
# Expected Output:
# 1 Apple
# 2 Banana
# 3 Cherry
        

6. Reverse a String

Reverse the string "interview" using slicing.

# Your code here
# Expected: weivretni
        

7. Merge Two Dictionaries

Merge two dictionaries into one in a single line.

dict1 = {"x": 1, "y": 2}
dict2 = {"z": 3}
# Your code here
# Expected: {"x": 1, "y": 2, "z": 3}
        

8. Check Even Numbers with all()

Given a list of numbers, check if all are even using all().

nums = [2, 4, 6, 8]
# Your code here
# Expected: True
        

9. Ternary Operator

Write a one-line ternary operator to check if a number is even or odd.

num = 11
# Your code here
# Expected: "Odd"
        

10. File Writing with Context Manager

Write "Python is powerful" to a file output.txt using a context manager.

# Your code here
        

11. F-String Formatting

Print: "Alice scored 95 marks" using f-strings.

name = "Alice"
score = 95
# Your code here