PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
    • Python Exercises
    • C Programming Exercises
    • C++ Exercises
  • Quizzes
  • Code Editor
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
Home » Python Exercises » Python Basic Exercise for Beginners: 40 Coding Problems with Solutions

Python Basic Exercise for Beginners: 40 Coding Problems with Solutions

Updated on: February 8, 2026 | 524 Comments

This Python exercise for beginners is designed to help you practice and improve your coding skills. This page contains over 40 Python exercises curated for beginners.

Each exercise includes a clear problem, a helpful hint, a complete solution, and a detailed explanation. This ensures you not only solve the problem but also understand why the solution works.

Also, See:

  • Python Exercises: A set of 17 topic specific exercises
  • Python Quizzes: Solve quizzes to test your knowledge of fundamental concepts.
  • Basic Python Quiz for beginners
  • Python Basics: Learn the basics of Python to solve this exercise.
  • Beginner Python Interview Questions

Tips and essential learning resources accompany each question. These will help you solve the exercise and become more familiar with Python basics.

This Python exercise covers questions on the following topics:

  • Python for loop and while loop
  • Python list, set, tuple, dictionary, input, and output
  • Use Online Python Code Editor to solve exercises.

Let us know if you have any alternative solutions in the comments section below. This will help other developers.

+ Table of Contents (40 Exercises)

Table of contents

  • Exercise 1. Arithmetic Product and Conditional Logic
  • Exercise 2. Cumulative Sum of a Range
  • Exercise 3. String Indexing and Even Slicing
  • Exercise 4. String Slicing and Substring Removal
  • Exercise 5. Variable Swapping (The In-Place Method)
  • Exercise 6. Calculating Factorial with a Loop
  • Exercise 7. List Manipulation: Add and Remove
  • Exercise 8. String Reversal
  • Exercise 9. Vowel Frequency Counter
  • Exercise 10. Finding Extremes (Min/Max) in a List
  • Exercise 11. Removing Duplicates from a List
  • Exercise 12. List Comparison and Boolean Logic
  • Exercise 13. Filtering Lists with Conditional Logic
  • Exercise 14. Substring Frequency Analysis
  • Exercise 15. Nested Loops for Pattern Generation
  • Exercise 16. Numerical Palindrome Check
  • Exercise 17. Merging Lists with Parity Filtering
  • Exercise 18. Integer Digit Extraction and Reversal
  • Exercise 19. Multi-Tiered Income Tax Calculation
  • Exercise 20. Nested Loops for Multiplication Tables
  • Exercise 21. Downward Half-Pyramid Pattern
  • Exercise 22. Custom Exponentiation Function
  • Exercise 23. Check Palindrome Number
  • Exercise 24. Generate Fibonacci Series
  • Exercise 25. Check Leap Year
  • Exercise 26. Merging Two Dictionaries
  • Exercise 27. Finding Common Elements (Intersections)
  • Exercise 28. Odd/Even List Splitter
  • Exercise 29. Word Length Analysis
  • Exercise 30. Word Frequency Counter (The Histogram)
  • Exercise 31. Print Alternate Prime Numbers
  • Exercise 32. Dictionary of Squares (Mapping Logic)
  • Exercise 33. Character Replacer (Data Sanitization)
  • Exercise 34. Print Reverse Number Pattern
  • Exercise 35. Digit Detection in Strings
  • Exercise 36. Capitalize First Letter (Title Case)
  • Exercise 37. Simple Countdown Timer
  • Exercise 38. File Creation and Basic I/O
  • Exercise 39. External File Word Counter
  • Exercise 40. Introduction to Classes (OOP)

Exercise 1. Arithmetic Product and Conditional Logic

Practice Problem: Write a Python function that accepts two integer numbers. If the product of the two numbers is less than or equal to 1000, return their product; otherwise, return their sum.

Exercise Purpose: Learn basic control flow and the use of if-else statements. Understand how code decisions change output based on a mathematical threshold.

Given Input:

  • Case 1: number1 = 20, number2 = 30
  • Case 2: number1 = 40, number2 = 30

Expected Output:

  • The result is 600
  • The result is 70

Refer:

  • Accept user input in Python
  • Calculate an Average in Python
Hint
  • Define a function that calculates the product two given numbers.
  • Use an if statement to compare that product against 1000 to decide whether to return the product or the sum.
Solution
def multiplication_or_sum(num1, num2):
    # Calculate product
    product = num1 * num2
    
    # Check if product is within the threshold
    if product <= 1000:
        return product
    else:
        return num1 + num2

# Testing Case 1
result = multiplication_or_sum(20, 30)
print("The result is", result)

# Testing Case 2
result = multiplication_or_sum(40, 30)
print("The result is", result)Code language: Python (python)

Explanation to Solution:

  • Function Definition: The code uses def to create a reusable block of logic, Inside the function multiply these two numbers and store their product in a variable.
  • Conditional Branching: The if product <= 1000 line acts as a gatekeeper, routing the program’s logic based on the calculated value.
  • Return Values: Instead of just printing, the function returns the value, allowing the calling code to decide how to display or use the result.

Exercise 2. Cumulative Sum of a Range

Practice Problem: Iterate through the first 10 numbers (0–9). In each iteration, print the current number, the previous number, and their sum.

Exercise Purpose: This exercise teaches “State Tracking.” In programming, you often need to remember a value from a previous loop iteration to calculate results in the current one. This is the basis for algorithms like Fibonacci sequences or running totals.

Given Input: Range: numbers = range(10)

Expected Output:

Printing current and previous number sum in a range(10)
Current Number 0 Previous Number 0 Sum: 0
Current Number 1 Previous Number 0 Sum: 1
Current Number 2 Previous Number 1 Sum: 3
....
Current Number 8 Previous Number 7 Sum: 15
Current Number 9 Previous Number 8 Sum: 17

Reference article for help:

  • Python range() function
  • Calculate sum and average in Python
Hint
  • Initialize a variable previous_num to 0 outside the loop.
  • At the end of each loop iteration, update previous_num with the value of the current_num.
Solution
print("Printing current and previous number sum in a range(10)")
previous_num = 0

# Loop from 0 to 9
for i in range(10):
    x_sum = previous_num + i
    print(f"Current Number {i} Previous Number {previous_num} Sum: {x_sum}")
    
    # Update previous_num for the next iteration
    previous_num = iCode language: Python (python)

Explanation to Solution:

  • Initialization: previous_num = 0 is set outside the loop so it persists across iterations.
  • for loop Iteration: The for i in range(10) loop automatically increments i from 0 to 9.
  • Next, display the current number (i), the previous number, and the addition of both numbers in each iteration of the loop.
  • State Update: The line previous_num = i is critical; it “shifts” the current value into the “memory” slot for the next cycle of the loop.

Exercise 3. String Indexing and Even Slicing

Practice Problem: Display only those characters which are present at an even index number in given string.

Exercise Purpose: Understand how data is stored in memory using zero-based indexing. In most languages, the first character is at position 0, the second at 1, and so on. Mastering indexing is vital for data parsing.

Given Input: String: "pynative"

Expected Output:

Original String is  pynative
Printing only even index chars
p
n
t
v
Hint
  • You can solve this using a for loop with a range that steps by 2. Iterate through the characters of the string using a loop and the range() function.
  • Use start = 0, stop = len(s) - 1, and step = 2. The step is 2 because we want only even index numbers.
  • Or by using Python’s built-in string slicing syntax [::2].
Solution
word = "pynative"
print("Original String is ", word)

# Method: Using list slicing
# format: [start:stop:step]
even_chars = word[0::2]

print("Printing only even index chars")
for char in even_chars:
    print(char)Code language: Python (python)

Explanation to Solution:

  • Zero-based Indexing: The character ‘p’ is at index 0, ‘y’ is at 1, ‘n’ is at 2.
  • Slicing [0::2]: This is a powerful Python feature. It tells the program: “Start at index 0, go to the end, and skip every 2nd character.”
  • Iteration: The for char in even_chars loop processes the resulting subset of characters individually.

Solution 2: Using loop

# accept input string from a user
word = input('Enter word ')
print("Original String:", word)

# get the length of a string
size = len(word)

# iterate a each character of a string
# start: 0 to start with first character
# stop: size-1 because index starts with 0
# step: 2 to get the characters present at even index like 0, 2, 4
print("Printing only even index chars")
for i in range(0, size - 1, 2):
    print("index[", i, "]", word[i])Code language: Python (python)

Exercise 4. String Slicing and Substring Removal

Practice Problem: Write a function to remove characters from a string starting from index 0 up to n and return a new string.

Exercise Purpose: This exercise demonstrates how to truncate data strings, a common data-cleaning task.

Given Input:

  • remove_chars("pynative", 4)
  • remove_chars("pynative", 2)

Expected Output:

  • tive
  • native
Hint
  • Use string slicing to get a substring
  • To remove the first n characters, you essentially want to keep everything from index n to the end of the string: string[n:].
Solution
def remove_chars(word, n):
    print('Original string:', word)
    # Extract string from index n to the end
    res = word[n:]
    return res

print("Removing characters from a string")
print(remove_chars("pynative", 4))
print(remove_chars("pynative", 2))Code language: Python (python)

Explanation to Solution:

  • Slicing word[n:]: By omitting the “stop” value in the slice, Python defaults to the very end of the string.
  • Flexibility: The function is designed to take n as an argument, making it reusable for any length of removal.
  • Memory: Note that strings in Python are immutable; this function doesn’t change the original string but creates and returns a new truncated version.

Also, try to solve Python string exercises

Exercise 5. Variable Swapping (The In-Place Method)

Practice Problem: Write a program to swap the values of two variables, a and b, without using a third temporary variable.

Exercise Purpose: This exercise will help you learn about memory efficiency and Python’s special tuple unpacking feature. In other languages like C or Java, you need a temporary variable to swap values safely. In Python, you can swap values in one line without risking data loss.

Given Input: a = 5, b = 10

Expected Output:

Before Swap: a = 5, b = 10
After Swap: a = 10, b = 5
Hint
  • In Python, you can use the syntax a, b = b, a.
  • This evaluates the right side (creating a tuple) and then assigns the values back to the left side simultaneously.
Solution
a = 5
b = 10
print(f"Before Swap: a = {a}, b = {b}")

# Simultaneous assignment (Tuple Unpacking)
a, b = b, a

print(f"After Swap: a = {a}, b = {b}")Code language: Python (python)

Explanation to Solution:

  • Simultaneous Evaluation: Python evaluates the entire right side (b, a) first, essentially holding both values in a temporary hidden structure (a tuple).
  • Assignment: It then unpacks those values into the variables on the left. This prevents the value of a from being overwritten by b before its original value can be moved.
  • Clean Code: This eliminates the need for three lines of code and an extra “temp” variable, making the script more readable.

Exercise 6. Calculating Factorial with a Loop

Practice Problem: Write a program that calculates the factorial of a given number (e.g., 5!) using a for loop.

Exercise Purpose: This exercise explores “Mathematical Accumulation.” A factorial (e.g., 5! = 5*4*3*2*1) requires you to maintain a running product across multiple iterations, which is a core pattern in scientific computing.

Given Input: number = 5

Expected Output: The factorial of 5 is 120

Hint
  • Initialize a factorial variable to 1.
  • Loop through a range from 1 to the given number, multiplying the factorial variable by the current loop index at each step.
Solution
num = 5
factorial = 1

# Loop from 1 to num (inclusive)
for i in range(1, num + 1):
    factorial = factorial * i

print(f"The factorial of {num} is {factorial}")Code language: Python (python)

Explanation to Solution:

  • Identity Element: We start factorial at 1 because multiplying by zero would ruin the entire calculation.
  • range(1, num + 1): Since the end of a range is exclusive, we use + 1 to ensure the loop includes the number 5.
  • Running Product: Each pass of the loop updates the value of factorial, building the final result step-by-step.

Exercise 7. List Manipulation: Add and Remove

Practice Problem: Create a list of 5 fruits. Add a new fruit to the end of the list, then remove the second fruit (at index 1).

Exercise Purpose: This exercise teaches “Dynamic Collection Management.” Lists are rarely static; being able to modify, expand, and prune them is essential for handling data like shopping carts, user lists, or inventory systems.

Given Input: fruits = ["apple", "banana", "cherry", "date", "elderberry"]

Expected Output: ['apple', 'cherry', 'date', 'elderberry', 'fig']

Hint
  • Use .append() to add an item to the end
  • and .pop(1) or del to remove the item at the specific index.
Solution
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Add a fruit to the end
fruits.append("fig")

# Remove the second fruit (index 1)
fruits.pop(1)

print(fruits)Code language: Python (python)

Explanation to Solution:

  • .append(): This method adds the new item without disturbing the existing order.
  • Zero-Based Indexing: In Python, the “second” item is actually at index 1 (0 is the first).
  • .pop(1): This removes the item at index 1 and “shifts” the remaining items (cherry, date, etc.) to the left to fill the gap, maintaining list integrity.

Exercise 8. String Reversal

Practice Problem: Write a program that takes a string and reverses it (e.g., “Python” becomes “nohtyP”).

Exercise Purpose: This exercise demonstrates “Sequence Slicing.” Strings in Python are sequences, and mastering the slicing syntax is a powerful shortcut for data manipulation that would take 5-10 lines of code in other languages.

Given Input: text = "Python"

Expected Output: Reversed: nohtyP

Hint
  • Use Python’s slicing notation [start:stop:step].
  • Setting the step to -1 tells Python to move through the sequence backwards.
Solution
text = "Python"

# Reversing using slicing
reversed_text = text[::-1]

print(f"Original: {text}")
print(f"Reversed: {reversed_text}")Code language: Python (python)

Explanation to Solution:

  • [::-1]: The first two colons imply “start at the very beginning” and “go to the very end.” The -1 indicates the direction of travel.
  • Immutability: This operation doesn’t change the original text variable; instead, it creates a new string in memory with the characters in reverse order.
  • Efficiency: This is the most efficient way to reverse a string in Python, utilizing optimized internal C code.

Exercise 9. Vowel Frequency Counter

Practice Problem: Write a program to count the total number of vowels (a, e, i, o, u) present in a given sentence.

Exercise Purpose: This exercise introduces “Membership Testing.” By checking if a character belongs to a specific group (the vowels), you learn how to filter data based on categories. This is a fundamental step toward building text-analysis tools or spam filters.

Given Input: sentence = "Learning Python is fun!"

Expected Output: Number of vowels: 6

Hint
  • Define a string containing all vowels "aeiou".
  • Loop through the sentence, convert each character to lowercase to ensure the check is case-insensitive, and increment a counter if the character exists in your vowel string.
Solution
sentence = "Learning Python is fun!"
vowels = "aeiou"
count = 0

# Convert to lowercase to handle 'A' and 'a' equally
for char in sentence.lower():
    if char in vowels:
        count += 1

print(f"Number of vowels: {count}")Code language: Python (python)

Explanation to Solution:

  • .lower(): This is essential for robust code. It ensures that “A” and “a” are both counted without needing to write a massive if statement for both cases.
  • The in Keyword: This is a highly optimized Python operator that checks for the existence of an item within a sequence (the string of vowels).
  • Counter Pattern: We use a simple integer (count) that “accumulates” every time the condition evaluates to True.

Exercise 10. Finding Extremes (Min/Max) in a List

Practice Problem: Given a list of integers, find and print both the largest and the smallest numbers.

Exercise Purpose: This exercise explores “Aggregate Functions.” While Python has built-in tools for this, understanding how to identify extremes is critical for data normalization, where you often need to find the range of a dataset before processing it.

Given Input: nums = [45, 2, 89, 12, 7]

Expected Output: Largest: 89 Smallest: 2

Hint
  • Python provides the max() and min() functions which iterate through a collection and return the extreme values in O(n) time.
Solution
nums = [45, 2, 89, 12, 7]

largest = max(nums)
smallest = min(nums)

print(f"Largest: {largest}")
print(f"Smallest: {smallest}")Code language: Python (python)

Explanation to Solution:

  • max(nums): Internally, this function assumes the first element is the largest, then compares it against every other element in the list, updating the “current winner” as it goes.
  • min(nums): Works identically to max, but tracks the lowest value found.
  • Algorithm Efficiency: These functions only need to pass through the list once, making them very fast even for lists with millions of items.

Exercise 11. Removing Duplicates from a List

Practice Problem: Write a script that takes a list containing duplicate items and returns a new list with only unique elements.

Exercise Purpose: This exercise teaches “Data De-duplication.” In real-world data science, datasets are often “messy” with repeating entries. Mastering the conversion between Lists (which allow duplicates) and Sets (which do not) is the fastest way to clean data.

Given Input: data = [1, 2, 2, 3, 4, 4, 4, 5]

Expected Output: Unique List: [1, 2, 3, 4, 5]

Hint

The easiest way to remove duplicates in Python is to convert the list into a set(), then convert it back into a list().

Solution
data = [1, 2, 2, 3, 4, 4, 4, 5]

# Set conversion removes duplicates automatically
unique_data = list(set(data))

print(f"Unique List: {unique_data}")Code language: Python (python)

Explanation to Solution:

  • set(data): A Set is a collection where every element must be unique. When you pass a list into a set, Python automatically discards any value it has already seen.
  • list(...): Since sets are unordered and do not support indexing, we convert the result back into a list so we can use it in standard list operations later.
  • Ordering Note: Converting to a set usually loses the original order of items. If order matters, you would need a loop or a dict.fromkeys() approach.

Exercise 12. List Comparison and Boolean Logic

Practice Problem: Write a function to return True if the first and last number of a given list is the same. If the numbers are different, return False.

Exercise Purpose: This exercise introduces “Collection Indexing” and “Boolean Flags.” Comparing data structure boundaries is common in pattern matching and data integrity checks.

Given Input:

  • numbers_x = [10, 20, 30, 40, 10]
  • numbers_y = [75, 65, 35, 75, 30]

Expected Output:

Given list: [75, 65, 35, 75, 30] | result is False
Given list: [10, 20, 30, 40, 10] | result is True
Hint

Use index 0 to access the first element and index -1 to access the very last element of the list.

Solution
def first_last_same(number_list):
    print("Given list:", number_list)
    
    first_num = number_list[0]
    last_num = number_list[-1]
    
    if first_num == last_num:
        return True
    else:
        return False

numbers_x = [10, 20, 30, 40, 10]
print("result is", first_last_same(numbers_x))

numbers_y = [75, 65, 35, 75, 30]
print("result is", first_last_same(numbers_y))Code language: Python (python)

Explanation to Solution:

  • Negative Indexing: Python allows [-1] to represent the last item in a list regardless of the list’s length. This is safer and cleaner than calculating len(list) - 1.
  • Equality Operator (==): This operator compares the values of the two objects and evaluates to a Boolean (True/False).
  • Logic Gate: The function provides a clear binary answer based on the structural properties of the input list.

Exercise 13. Filtering Lists with Conditional Logic

Practice Problem: Iterate through a given list of numbers and print only those numbers which are divisible by 5.

Exercise Purpose: This exercise teaches the use of the modulo operator (%) and loop filtering. In data processing, you often need to sift through large datasets to extract subsets that meet mathematical criteria.

Given Input: num_list = [10, 20, 33, 46, 55]

Expected Output:

Divisible by 5:
10, 20, 55
Hint
  • Use a for loop to go through each number.
  • Inside the loop, check if number % 5 == 0. If the remainder is zero, the number is divisible by 5.
Solution
num_list = [10, 20, 33, 46, 55]
print("Given list is", num_list)
print("Divisible by 5:")

# Iterate through each element
for num in num_list:
    # Check divisibility
    if num % 5 == 0:
        print(num)Code language: Python (python)

Explanation to Solution:

  • for num in num_list: This construct allows the program to visit every item in the collection without needing to track indices manually.
  • num % 5 == 0: The modulo operator returns the remainder. If the remainder of division by 5 is 0, the number is a multiple of 5.
  • Filtering Logic: Only when the if condition evaluates to True does the print function execute, effectively “filtering” the list.

Also, try to solve Python list Exercise

Exercise 14. Substring Frequency Analysis

Practice Problem: Write a program to find how many times the substring “Emma” appears in a given string.

Exercise Purpose: Text analysis and pattern matching are core pillars of programming. This exercise introduces searching for a “needle in a haystack,” a fundamental concept for building search engines or data validation tools.

Given Input:

  • str_x = "Emma is good developer. Emma is a writer"

Expected Output: Emma appeared 2 times

Hint

Python strings have a built-in method called .count() that can search for occurrences of a specific sequence of characters.

Solution
str_x = "Emma is good developer. Emma is a writer"
count = str_x.count("Emma")
print(f"Emma appeared {count} times")Code language: Python (python)

Explanation to Solution:

  • str_x.count("Emma"): This is a high-level abstraction that handles the complex logic of scanning the string and incrementing a counter internally.
  • Case Sensitivity: Note that string methods like count are case-sensitive; searching for “emma” (lowercase) would return 0.

Exercise 15. Nested Loops for Pattern Generation

Practice Problem: Print the following pattern where each row contains a number repeated a specific number of times based on its value.

1 
2 2
3 3 3
4 4 4 4
5 5 5 5 5

Exercise Purpose: Pattern printing is a classic way to learn “Nested Loops.” You coordinate an outer loop for rows and an inner loop for columns or repetitions. This improves spatial logic and control over output formatting.

Given Input: Range: 1 to 5

Expected Output: (The pattern shown above)

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
Hint
  • The outer loop should iterate from 1 to 5.
  • The inner loop should repeat the current number of the outer loop based on its value (e.g., when the outer number is 3, the inner loop runs 3 times).
Solution
# Outer loop for rows
for num in range(1, 6):
    # Inner loop for repetition
    for i in range(num):
        print(num, end=" ") # end=" " keeps it on the same line
    # New line after each row
    print("\n")Code language: Python (python)

Explanation to Solution:

Notice that each row contains the same number repeated, and the number of repetitions increases with the row number.

  • Nested Loops: The outer loop num sets the “context” for the row. The inner loop i performs the work for that specific row.
  • end=" ": By default, print() adds a newline. Overriding this with a space allows multiple numbers to appear side-by-side.
  • Formatting: The final print("\n") acts as a “carriage return,” starting the next row of the pattern on a clean line.

Exercise 16. Numerical Palindrome Check

Practice Problem: Write a program to check if a given number is a palindrome (reads the same forwards and backwards).

Exercise Purpose: This exercise introduces the idea of “Reversing Logic.” Reversing a string is simple, but reversing an integer takes some math, like using division and modulo, or changing its type. This shows how data types can work differently.

Given Input:

  • Case 1: number = 121
  • Case 2: number = 125

Expected Output:

Number 125 is not palindrome number
Number 121 is palindrome number

Refer: Python Programs to Check Palindrome Number

Hint

Use a simple “Pythonic” way str(number) to convert the number to a string and check if str_num == str_num[::-1].

Solution
def check_palindrome(number):
    print("original number", number)
    # Convert to string to reverse easily
    original_str = str(number)
    reversed_str = original_str[::-1]
    
    if original_str == reversed_str:
        print("Yes. given number is palindrome number")
    else:
        print("No. given number is not palindrome number")

check_palindrome(121)
check_palindrome(125)Code language: Python (python)

Explanation to Solution:

  • str(number): Type casting is used here to transform a math object into a sequence of characters.
  • [::-1]: This is the slice notation for reversing a sequence. It tells Python to step through the entire string backwards.
  • Boolean Comparison: The == operator determines if the two states (original vs. mirror) are identical.

Exercise 17. Merging Lists with Parity Filtering

Practice Problem: Create a new list from two given lists such that the new list contains odd numbers from the first list and even numbers from the second list.

Given Input:

  • list1 = [10, 20, 25, 30, 35]
  • list2 = [40, 45, 60, 75, 90]

Expected Output: [25, 35, 40, 60, 90]

Note: Try to solve the Python list exercises

Hint
  • Create an empty result list.
  • Use two separate loops to iterate through each source list and append only the numbers that satisfy the odd/even condition.
Solution
def merge_list(list1, list2):
    result_list = []
    
    # Get odd numbers from list1
    for num in list1:
        if num % 2 != 0:
            result_list.append(num)
            
    # Get even numbers from list2
    for num in list2:
        if num % 2 == 0:
            result_list.append(num)
            
    return result_list

list1 = [10, 20, 25, 30, 35]
list2 = [40, 45, 60, 75, 90]
print("result list:", merge_list(list1, list2))Code language: Python (python)

Explanation to Solution:

  • result_list = []: Initializing an empty list is a standard pattern for gathering data dynamically.
  • num % 2 != 0: This checks for “not divisible by 2,” effectively finding odd numbers.
  • append(): This method adds elements to the end of the new list, preserving the order in which they were found in the source lists.

Exercise 18. Integer Digit Extraction and Reversal

Practice Problem: Write a program to extract each digit from an integer in the reverse order.

Exercise Purpose: This exercise explores “Mathematical Parsing.” Instead of converting a number to a string, use the modulo operator (%) and floor division (//) to isolate digits. This is common in low-level programming and algorithm challenges where type conversion is restricted.

Given Input: number = 7536

Expected Output: 6 3 5 7

Refer: Python Programs to Reverse an Integer Number

Hint
  • Use number % 10 to get the last digit.
  • Then, use number // 10 to “chop off” that last digit and repeat the process in a loop until the number becomes zero.
Solution
number = 7536
print("Given Number:", number)

while number > 0:
    # Get the last digit
    digit = number % 10
    
    # Remove the last digit from number
    number = number // 10
    
    print(digit, end=" ")Code language: Python (python)

Explanation to Solution:

  • number % 10: This operation returns the remainder of the number divided by 10, which is always the rightmost digit.
  • number // 10: Floor division removes the decimal part, effectively shifting the number one decimal place to the right.
  • end=" ": This keeps the output on a single line, separated by spaces, rather than printing each digit on a new line.

Exercise 19. Multi-Tiered Income Tax Calculation

Practice Problem: Calculate income tax for a given income based on these rules:

  • First $10,000: 0% tax
  • Next $10,000: 10% tax
  • Remaining income: 20% tax

Exercise Purpose: This exercise introduces “Tax Brackets” logic, a classic example of complex conditional branching. It shows how to calculate values cumulatively instead of applying a single percentage to the entire amount.

Given Input: income = 45000

Expected Output: Total income tax to pay is 6000

Hint
  • Subtract the brackets one by one.
  • For an income of 45,000: the first 10k is free, the next 10k is taxed at 10% (1,000), and the remaining 25k is taxed at 20% (5,000).
Solution
income = 45000
tax_payable = 0
print("Given income:", income)

if income <= 10000:
    tax_payable = 0
elif income <= 20000:
    # Tax on first 10k is 0. Tax on the rest is 10%
    tax_payable = (income - 10000) * 10 / 100
else:
    # First 10,000 (0% tax)
    # Next 10,000 (10% tax = 1,000)
    tax_payable = 0 + (10000 * 10 / 100) 
    # Remaining income (20% tax)
    tax_payable += (income - 20000) * 20 / 100

print("Total income tax to pay is", tax_payable)Code language: Python (python)

Explanation to Solution:

  • Cumulative Logic: The code doesn’t just check one condition; it accounts for every bracket the income “passes through.”
  • elif chain: This ensures that only the relevant calculation block is executed based on the total income range.
  • Mathematical Precision: By breaking the calculation into steps, you avoid the common mistake of taxing the entire 45,000 at the highest rate.

Exercise 20. Nested Loops for Multiplication Tables

Practice Problem: Print a multiplication table from 1 to 10 in a formatted grid.

Exercise Purpose: To master “Matrix Generation.” This builds on the nested loop concepts from Exercise 8 and applies them to generate a structured data table. This is essential for understanding how to populate 2D arrays or generate spreadsheets.

Given Input: Range: 1 to 10

Expected Output:

1  2  3  4  5  6  7  8  9  10 		
2 4 6 8 10 12 14 16 18 20
... (up to 10)

Refer:

  • Nested loops in Python
  • Create Multiplication Table in Python
Hint
  • Use an outer loop for the rows (1 to 10) and an inner loop for the columns (1 to 10).
  • Inside the inner loop, multiply the two loop variables.
Solution
for i in range(1, 11):
    for j in range(1, 11):
        # Print product followed by a tab space
        print(i * j, end="\t")
    print("\n")Code language: Python (python)

Explanation to Solution:

  • range(1, 11): Remember that Python’s range is exclusive of the stop value, so we use 11 to include 10.
  • \t (Tab Character): This is a string escape sequence that ensures the numbers align in neat columns regardless of whether they are one or two digits long.
  • Row/Column Coordination: For every iteration of the outer loop (i), the inner loop (j) completes a full cycle of 1 to 10.

Exercise 21. Downward Half-Pyramid Pattern

Practice Problem: Print a downward half-pyramid pattern using stars (*).

Exercise Purpose: Learn about reverse indexing. Controlling loop boundaries in reverse is important for algorithms that process data from end to beginning.

Given Input: Rows: 5

Expected Output:

* * * * * 
* * * *
* * *
* *
*

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
Hint
  • Use a loop that starts at 5 and ends at 0, moving backwards by -1.
  • In each step, print the star character multiplied by the current loop value.
Solution
# Loop from 5 down to 1
for i in range(5, 0, -1):
    for j in range(0, i):
        print("*", end=" ")
    print("\n")Code language: Python (python)

Explanation to Solution:

  • range(5, 0, -1): The third argument -1 is the “step.” It tells the loop to decrement the value of i in each iteration.
  • String Multiplication (Alternative): In Python, you could also write print("* " * i), which is a more concise “Pythonic” way to repeat characters.
  • Inner Loop Constraint: The inner loop’s range is bound by the current value of the outer loop, causing the line length to decrease over time.

Exercise 22. Custom Exponentiation Function

Practice Problem: Write a function called exponent(base, exp) that returns an integer value of the base raised to the power of the exponent.

Exercise Purpose: Learn about “Accumulator Patterns.” Although Python has a built-in power operator (**), making your own version shows how repeated multiplication works and how functions return results to the main program.

Given Input: base = 2, exp = 5

Expected Output: 2 raises to the power of 5: 32

Hint
  • Initialize a result variable to 1.
  • Use a loop that runs exp times, and in each iteration, multiply the result by the base.
Solution
def exponent(base, exp):
    num = exp
    result = 1
    # Repeat multiplication 'exp' times
    while num > 0:
        result = result * base
        num = num - 1
    print(base, "raises to the power of", exp, "is:", result)

exponent(2, 5)
exponent(5, 4)Code language: Python (python)

Explanation to Solution:

  • Base Case: result starts at 1 because 1 is the identity element for multiplication (anything multiplied by 1 remains itself).
  • The while Loop: This controls the number of multiplications. Each cycle represents one “power.”
  • Function Reusability: By passing base and exp as parameters, the same block of code can calculate 25, 54, or any other combination.

Exercise 23. Check Palindrome Number

Practice Problem: Write a program to check if a given number is a palindrome. A palindrome number remains the same when its digits are reversed (e.g., 121, 545).

Exercise Purpose: This exercise teaches “Algorithmic Reversal.” While strings are easy to reverse in Python, reversing a number mathematically using the modulo (%) and floor division (//) operators deepens understanding of how integers are stored in memory and how to manipulate digits individually.

Given Input: number = 121

Expected Output:

Original number 121
Yes. given number is palindrome number

Refer:

  • Python Programs to Check Palindrome Number
  • Python Programs to Reverse an Integer Number
Hint
  • You can reverse the number by repeatedly extracting the last digit (num % 10) and building a new number.
  • Alternatively, for a “Pythonic” shortcut, convert the integer to a string and use slicing [::-1] to compare it to its original form.
Solution
def check_palindrome(number):
    # Convert to string to easily reverse
    str_num = str(number)
    reverse_str = str_num[::-1]
    
    if str_num == reverse_str:
        print(f"Original number {number}")
        print("Yes. given number is palindrome number")
    else:
        print(f"Original number {number}")
        print("No. given number is not palindrome number")

check_palindrome(121)Code language: Python (python)

Explanation to Solution:

  • str(number): Converts the integer into a sequence of characters so we can treat it like a list.
  • [::-1]: This is the slice notation for “start at the end, end at the beginning, and move backwards by 1.” It effectively mirrors the string.
  • if str_num == reverse_str: A boolean comparison that checks for exact symmetry.

Exercise 24. Generate Fibonacci Series

Practice Problem: Write a program to print the first 15 terms of the Fibonacci series. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding ones.

Exercise Purpose: The Fibonacci sequence is a classic way to learn about state management in loops. You keep track of two changing variables at once to find the next number, which helps you see how data moves through each step.

Given Input: Terms = 15

Expected Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Refer: Generate Fibonacci Series in Python

Hint
  • Initialize two variables, num1 = 0 and num2 = 1.
  • In each iteration of a loop, the next number is num1 + num2.
  • Then, update num1 to be num2, and num2 to be the new sum.
Solution
num1, num2 = 0, 1
print("Fibonacci series:")

for i in range(15):
    print(num1, end="  ")
    # Calculate next term
    res = num1 + num2
    # Update values for next iteration
    num1 = num2
    num2 = resCode language: Python (python)

Explanation to Solution:

  • num1, num2 = 0, 1: Python’s tuple unpacking allows for clean initialization of multiple variables.
  • res = num1 + num2: This creates the new term based on the current state of the two pointers.
  • num1 = num2 and num2 = res: This “shifts” the window forward by one position, preparing the variables for the next cycle.

Exercise 25. Check Leap Year

Practice Problem: Write a program that takes a year as input and determines if it is a leap year.

A leap year is a year in the Gregorian calendar that contains an extra day, making it 366 days long instead of the usual 365. This extra day, February 29th, is added to keep the calendar synchronized with the Earth’s revolution around the Sun.

Rules for leap years: a year is a leap year if it’s divisible by 4, unless it’s also divisible by 100 but not by 400.

Exercise Purpose: This exercise is vital for mastering “Complex Conditional Logic.” A leap year isn’t just “every 4 years”; there are specific exceptions for century years. This forces the programmer to use nested if statements or compound logical operators (and/or).

Given Input: year = 2024

Expected Output: 2024 is a leap year

Hint
  • A year is a leap year if it is divisible by 4. However, if it is divisible by 100, it is NOT a leap year UNLESS it is also divisible by 400.
Solution
def is_leap(year):
    # Standard Leap Year Logic
    if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
        print(f"{year} is a leap year")
    else:
        print(f"{year} is not a leap year")

is_leap(2024)
is_leap(2100)Code language: Python (python)

Explanation to Solution:

  • year % 4 == 0: Checks the basic 4-year cycle.
  • year % 100 != 0: Excludes years like 1900 or 2100, which are divisible by 4 but are not leap years.
  • or (year % 400 == 0): The “exception to the exception,” ensuring years like 2000 are correctly identified as leap years.

Exercise 26. Merging Two Dictionaries

Practice Problem: Write a program that takes two separate dictionaries and merges them into one single dictionary.

Exercise Purpose: This introduces “Key-Value Consolidation.” Merging dictionaries is a common task when combining configuration files or user profiles. It also teaches you about “Key Overwriting”—what happens when both dictionaries share the same key.

Given Input:

dict1 = {"name": "Alice", "age": 25}
dict2 = {"city": "New York", "job": "Engineer"}Code language: Python (python)

Expected Output:

{'name': 'Alice', 'age': 25, 'city': 'New York', 'job': 'Engineer'}
Hint
  • In modern Python (3.9+), you can use the union operator | to merge two dictionaries effortlessly.
  • For older versions, the .update() method is used.
Solution
dict1 = {"name": "Alice", "age": 25}
dict2 = {"city": "New York", "job": "Engineer"}

# Modern Python merge (Union Operator)
merged_dict = dict1 | dict2

print(merged_dict)Code language: Python (python)

Explanation to Solution:

  • The | Operator: This creates a new dictionary containing the keys and values of both inputs.
  • Conflict Resolution: If both dictionaries had an “age” key, the value from the second dictionary (dict2) would prevail in the final merge.
  • Immutability: This method preserves the original dict1 and dict2 while creating a third, combined object.

Exercise 27. Finding Common Elements (Intersections)

Practice Problem: Take two lists and find the elements that appear in both. Use Sets to perform the operation.

Exercise Purpose: This exercise explores “Mathematical Set Operations.” Finding intersections is vital for recommendation engines (e.g., finding “mutual friends” or “shared interests”). It demonstrates why using the right data structure (Set) is more efficient than nested loops.

Given Input:

list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]Code language: Python (python)

Expected Output: Common Elements: {4, 5}

Hint
  • Convert both lists to sets.
  • Use the & operator (Intersection) to find the elements that exist in both sets.
Solution
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]

set_a = set(list_a)
set_b = set(list_b)

# Find common elements using intersection
common = set_a & set_b

print(f"Common Elements: {common}")Code language: Python (python)

Explanation to Solution:

  • set_a & set_b: The ampersand represents the “Intersection” operation. It returns a set containing only items that are present in both set_a AND set_b.
  • Performance: Doing this with sets is significantly faster than using nested for loops, as set lookups are nearly instantaneous (O(1) average case).
  • Result Type: The output is a set {4, 5}, which effectively highlights that we are looking for a unique collection of shared items.

Exercise 28. Odd/Even List Splitter

Practice Problem: Start with a list of 10 numbers. Iterate through them and sort them into two separate lists: one for even numbers and one for odd numbers.

Given Input: numbers = [12, 7, 34, 21, 5, 10, 8, 3, 19, 2]

Expected Output:

Even numbers: [12, 34, 10, 8, 2]
Odd numbers: [7, 21, 5, 3, 19]
Hint
  • Create two empty lists at the start.
  • Use a for loop combined with an if-else statement.
  • Remember, a number is even if num % 2 == 0.
Solution
numbers = [12, 7, 34, 21, 5, 10, 8, 3, 19, 2]
evens = []
odds = []

for num in numbers:
    if num % 2 == 0:
        evens.append(num)
    else:
        odds.append(num)

print(f"Even numbers: {evens}")
print(f"Odd numbers: {odds}")Code language: Python (python)

Explanation to Solution:

  • % 2 == 0: The modulo operator checks for a remainder. If a number divided by 2 has no remainder, it is mathematically even.
  • .append(): This method dynamically grows our target lists as the loop finds matching candidates.
  • Logical Branching: The if-else structure ensures that every number is placed in exactly one category, maintaining the integrity of the original dataset.

Exercise 29. Word Length Analysis

Practice Problem: Create a list of 5 words. Write a loop that iterates through the list and prints each word alongside its character count.

Exercise Purpose: This exercise introduces “Metadata Extraction.” Often, you aren’t just interested in the data itself, but in its properties. In web development, this logic is used to validate if a user’s password or username meets specific length requirements.

Given Input: words = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

Expected Output:

Apple - 5 Banana - 6 Cherry - 6 Date - 4 Elderberry - 10
Hint

Use a for loop to access each word and the built-in len() function to calculate the number of letters.

Solution
words = ["Apple", "Banana", "Cherry", "Date", "Elderberry"]

for word in words:
    length = len(word)
    print(f"{word} - {length}")Code language: Python (python)

Explanation to Solution:

  • len(): This is a universal Python function that returns the number of items in a sequence (in this case, characters in a string).
  • String Interpolation (f-strings): We use f"{word} - {length}" to create a clean, readable output format that combines variables and static text.
  • Sequential Processing: The loop ensures that the operation is performed on every item in the list automatically, regardless of how many words are added later.

Exercise 30. Word Frequency Counter (The Histogram)

Practice Problem: Write a program that counts how many times each word appears in a given paragraph and stores these counts in a dictionary.

Exercise Purpose: This is a classic “Natural Language Processing” (NLP) task. It teaches you how to map data to occurrences, which is the logic used by search engines to index web pages or by social media platforms to identify trending hashtags.

Given Input: text = "apple banana apple cherry banana apple"

Expected Output: {'apple': 3, 'banana': 2, 'cherry': 1}

Hint
  • Split the text into a list of words.
  • Iterate through the list; if a word is already in the dictionary, increase its value by 1.
  • If it isn’t, add it with a starting value of
Solution
text = "apple banana apple cherry banana apple"
words = text.split()
frequency = {}

for word in words:
    if word in frequency:
        frequency[word] += 1
    else:
        frequency[word] = 1

print(frequency)Code language: Python (python)

Explanation to Solution:

  • .split(): This breaks the string into a list of individual strings, allowing us to process them one by one.
  • Dictionary Membership: if word in frequency checks if the word has already been “seen” by the script.
  • Incrementing Values: By using the word as a key and the count as a value, we create a high-speed lookup table of the paragraph’s content.

Exercise 31. Print Alternate Prime Numbers

Practice Problem: Write a program to find all prime numbers up to 20, but only print every second (alternate) prime number found.

Exercise Purpose: This exercise combines “Nested Loops” (to check for primality) with “Step Logic.” It requires the programmer to first identify a subset of data and then apply a secondary filter, a common task in data reporting.

Given Input: Limit = 20

Expected Output: 2, 5, 11, 17

Refer:

  • Python Programs to Check Prime Number
  • Python Programs to Print alternate Prime Numbers
Hint
  • First, create a list of all primes between 2 and 20.
  • Once the list is complete, use list slicing with a step of 2 (primes[::2]) to print the alternate values.
Solution
primes = []

for num in range(2, 21):
    # Check if number is prime
    for i in range(2, int(num**0.5) + 1):
        if num % i == 0:
            break
    else:
        primes.append(num)

# Print alternate primes
alternate_primes = primes[::2]
print(alternate_primes)Code language: Python (python)

Explanation to Solution:

  • for...else loop: A unique Python feature where the else block executes only if the for loop completes without hitting a break. This is perfect for prime checking.
  • num**0.5: Efficiency trick—you only need to check factors up to the square root of a number.
  • primes[::2]: The slicing engine skips every other element in the list, fulfilling the “alternate” requirement

Exercise 32. Dictionary of Squares (Mapping Logic)

Practice Problem: Create a dictionary where the keys are numbers from 1 to 10 and the values are the squares of those numbers (e.g., 2: 4, 3: 9).

Exercise Purpose: This exercise explores “Data Mapping.” It demonstrates how dictionaries can be used to store pre-calculated mathematical relationships, essentially acting as a “lookup table” that can replace expensive repetitive calculations.

Given Input: Range: 1 to 10

Expected Output:

{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
Hint
  • Use range(1, 11) and a loop to populate the dictionary.
  • You can assign values using the syntax dict[key] = value.
Solution
squares = {}

for i in range(1, 11):
    squares[i] = i * i

print(squares)Code language: Python (python)

Explanation to Solution:

  • range(1, 11): This provides the “keys” for our dictionary.
  • i * i: This calculates the square of the current number.
  • Key-Value Assignment: The line squares[i] = i * i creates a permanent link between the input number and its squared result within the dictionary structure.

Exercise 33. Character Replacer (Data Sanitization)

Practice Problem: Ask the user for a sentence. Replace every empty space in that sentence with an underscore (_) and print the final result.

Exercise Purpose: This exercise focuses on “String Sanitization.” In web development and file management, spaces are often problematic (especially in URLs or file paths). Learning to replace characters is a critical skill for preparing data for storage or transmission.

Given Input: "I love coding in Python"

Expected Output: I_love_coding_in_Python

Hint

Python strings have a built-in method called .replace(old, new) that scans the entire string and swaps characters for you.

Solution
user_sentence = input("Enter a sentence: ")

# Replace space with underscore
sanitized_sentence = user_sentence.replace(" ", "_")

print(sanitized_sentence)Code language: Python (python)

Explanation to Solution:

  • .replace(" ", "_"): This method is “Global,” meaning it doesn’t just find the first space; it finds every space in the string and replaces it.
  • Immutability: Remember that user_sentence itself isn’t changed; replace() creates a new string which we store in sanitized_sentence.
  • Input Handling: By using input(), the program can handle any sentence the user provides, making it a flexible utility script.

Exercise 34. Print Reverse Number Pattern

Practice Problem: Print a downward number pattern where each row starts with a decreasing value.

Exercise Purpose: In this exercise, you will learn about range control and practice using negative steps in loops to move backwards. This skill is important for algorithms that process data from the end of a file to the beginning.

Given Input: Rows = 5

Expected Output:

5 4 3 2 1 
4 3 2 1
3 2 1
2 1
1

Refer:

  • Print Pattern using for loop
  • Nested loops in Python
Hint
  • You need two loops. The outer loop should start at 5 and go down to 1.
  • The inner loop should start at the current value of the outer loop and go down to 1.
Solution
rows = 5
# Outer loop for number of rows
for i in range(rows, 0, -1):
    # Inner loop for printing numbers in each row
    for j in range(i, 0, -1):
        print(j, end=' ')
    print("") # New lineCode language: Python (python)

Explanation to Solution:

  • range(rows, 0, -1): The -1 argument is the step. It tells Python to count backwards.
  • print(j, end=' '): By overriding the default newline with a space, we keep the numbers on the same horizontal line.
  • print(""): This simple empty print statement acts as a “carriage return” to start the next row of the pattern.

Exercise 35. Digit Detection in Strings

Practice Problem: Write a program to check if a user-entered string contains any numeric digits. Use a for loop to examine each character.

Exercise Purpose: This exercise will help you learn about string traversal and character analysis. In software development, these skills are important for tasks like checking if a username has forbidden characters or if a password is complex enough.

Given Input: input_string = "Python3"

Expected Output: The string 'Python3' contains digits: True

Hint
  • Iterate through the string using a for loop.
  • For each character, use the built-in .isdigit() method.
  • If you find even one digit, you can set a flag to True and break the loop.
Solution
user_input = "Python3"
contains_digit = False

# Iterate through each character
for char in user_input:
    if char.isdigit():
        contains_digit = True
        break  # Exit early since we found one

print(f"The string '{user_input}' contains digits: {contains_digit}")Code language: Python (python)

Explanation to Solution:

  • Flag Pattern: We initialize contains_digit as False. This “flag” only flips if a specific condition is met.
  • .isdigit(): This character method returns True if the character is a numeric value (0-9) and False otherwise.
  • break: This keyword is an efficiency tool. Once a single digit is found, there is no need to check the remaining characters, saving processing time.

Exercise 36. Capitalize First Letter (Title Case)

Practice Problem: Write a program to capitalize the first letter of each word in a given string without using the built-in .title() method.

Exercise Purpose: In this exercise, you will learn about “Tokenization” and “String Re-assembly.” You will split a sentence into words, change them, and then put the sentence back together. This helps you practice working with complex data structures.

Given Input: text = "hello world from python"

Expected Output: Hello World From Python

Hint
  • Use the .split() method to turn the string into a list of words.
  • Loop through the list, use .capitalize() on each word, and then use " ".join() to merge them back into a single sentence.
Solution
text = "hello world from python"

# Split the string into a list of words
words = text.split()
capitalized_words = []

for word in words:
    # Capitalize each word and add to the new list
    capitalized_words.append(word.capitalize())

# Join the list back into a single string
result = " ".join(capitalized_words)
print(result)Code language: Python (python)

Explanation to Solution:

  • .split(): By default, this breaks a string into a list wherever there is a space. "hello world" becomes ["hello", "world"].
  • .capitalize(): This method turns the first character of a string to uppercase and the rest to lowercase.
  • " ".join(): This is the inverse of split. It takes a list and glues the items together using the string it is called on (in this case, a space) as the adhesive.

Exercise 37. Simple Countdown Timer

Practice Problem: Create a countdown timer that starts from a given number and counts down to zero using a while loop.

Exercise Purpose: In this exercise, you will learn about loop termination logic and time delay management. Knowing how to control the flow of your code in real time is important for making animations, game loops, or automated scripts.

Given Input: start_count = 5

Expected Output: 5 4 3 2 1 Blast off!

Hint
  • Use a while loop that continues as long as the counter is greater than 0.
  • Inside the loop, print the current value and then subtract 1 from the counter.
Solution
import time

count = 5

while count > 0:
    print(count)
    # Pause the program for 1 second
    time.sleep(1)
    # Decrement the counter
    count -= 1

print("Blast off!")Code language: Python (python)

Explanation to Solution:

  • while count > 0: This condition ensures the loop runs exactly as many times as specified. Once count hits 0, the condition becomes False and the loop stops.
  • time.sleep(1): This function from the time module pauses execution for one second, making the output feel like a real clock.
  • count -= 1: This is shorthand for count = count - 1. Without this line, the loop would be “infinite” because count would always stay at 5.

Exercise 38. File Creation and Basic I/O

Practice Problem: Write a program that creates a new text file named notes.txt, writes three separate lines of text to it, and then reads that file back to display the contents in the console.

Exercise Purpose: This exercise introduces “Persistent Storage.” Unlike variables that disappear when the program stops, files allow you to save data to the hard drive. Learning the open(), write(), and read() workflow is essential for building logging systems and saving user settings.

Given Input: Lines to write:

  1. “Hello, this is my first note.”
  2. “Python file handling is simple.”
  3. “End of file.”

Expected Output:

notes.txt

Hello, this is my first note.
Python file handling is simple.
End of file.
Hint
  • Use the with open("notes.txt", "w") statement to ensure the file is properly closed after writing.
  • Use the "w" mode for writing and the "r" mode for reading.
Solution
# Part 1: Writing to the file
with open("notes.txt", "w") as file:
    file.write("Hello, this is my first note.\n")
    file.write("Python file handling is simple.\n")
    file.write("End of file.\n")

# Part 2: Reading from the file
print("Reading file contents:")
with open("notes.txt", "r") as file:
    content = file.read()
    print(content)Code language: Python (python)

Explanation to Solution:

  • with open(...): Known as a “Context Manager,” this ensures that Python automatically closes the file even if an error occurs, preventing memory leaks or file corruption.
  • \n: This is the “newline” character. Without it, all three sentences would be squashed together on a single line in the text file.
  • "w" vs "r": The mode "w" (Write) will overwrite the file if it already exists, while "r" (Read) opens it for viewing only.

Exercise 39. External File Word Counter

Practice Problem: Write a script that opens an existing .txt file and counts the total number of words it contains.

Exercise Purpose: This exercise teaches “Data Parsing.” In professional environments, you rarely work with data you typed into the code yourself; you almost always pull data from external sources. This script simulates basic text-mining techniques used to analyze documents or logs.

Given Input:

An external file sample.txt containing: “Coding is the language of the future.”

Expected Output: The file contains 7 words.

Hint
  • Read the entire content of the file into a string, then use the .split() method to break that string into a list of words.
  • The length of that list is your word count.
Solution
# Assuming 'sample.txt' exists with some text
try:
    with open("sample.txt", "r") as file:
        data = file.read()
        words = data.split()
        word_count = len(words)
        print(f"The file contains {word_count} words.")
except FileNotFoundError:
    print("Error: The file 'sample.txt' was not found.")Code language: Python (python)

Explanation to Solution:

  • data.split(): By default, split() breaks a string at every space or newline. This effectively creates a list where every element is a single word.
  • len(words): Since words is now a list, the length of the list directly corresponds to the count of words in the document.
  • try-except: This is a bonus safety feature. If the file is missing, the program won’t “crash” with a scary error; instead, it will print a polite message explaining what happened.

Exercise 40. Introduction to Classes (OOP)

Practice Problem: Create a Car class with attributes for make, model, and year. Include a method called start_engine() that prints a formatted string describing the car starting up.

Exercise Purpose: This exercise introduces Object-Oriented Programming (OOP). Instead of just writing functions, you are creating a “Blueprint” (the Class) to generate “Objects” (the specific cars). This is how modern software is built, allowing you to organize code into logical, reusable components.

Given Input: Make: “Toyota”, Model: “Camry”, Year: 2022

Expected Output: The 2022 Toyota Camry's engine is now running!

Hint

Use the __init__ method to initialize your attributes and the self keyword to refer to the specific instance of the car being used.

Solution
class Car:
    def __init__(self, make, model, year):
        # Setting up attributes
        self.make = make
        self.model = model
        self.year = year

    def start_engine(self):
        # A method that uses the object's attributes
        print(f"The {self.year} {self.make} {self.model}'s engine is now running!")

# Creating an object (an instance of the class)
my_car = Car("Toyota", "Camry", 2022)

# Calling the method
my_car.start_engine()Code language: Python (python)

Explanation to Solution:

  • __init__: This is the “Constructor.” It runs automatically the moment you create a new car, setting its identity (Toyota, Camry, etc.).
  • self: This is a placeholder for the specific object. It tells Python, “use this car’s year” rather than just a generic variable named year.
  • Encapsulation: By grouping the data (attributes) and the actions (methods) together, your code becomes modular and much easier to manage as your program grows.

Filed Under: Python, Python Basics, Python Exercises

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Basics Python Exercises

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Loading comments... Please wait.

In: Python Python Basics Python Exercises
TweetF  sharein  shareP  Pin

  Python Exercises

  • All Python Exercises
  • Basic Exercise for Beginners
  • Intermediate Python Exercises
  • Input and Output Exercise
  • Loop Exercise
  • Functions Exercise
  • String Exercise
  • Data Structure Exercise
  • List Exercise
  • Dictionary Exercise
  • Set Exercise
  • Tuple Exercise
  • Date and Time Exercise
  • OOP Exercise
  • File Handling Exercise
  • Python JSON Exercise
  • Random Data Generation Exercise
  • NumPy Exercise
  • Pandas Exercise
  • Matplotlib Exercise
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com

Advertisement