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 Input and Output Exercise: 20+ Coding Problems with Solutions

Python Input and Output Exercise: 20+ Coding Problems with Solutions

Updated on: March 26, 2026 | 111 Comments

Whether you’re building interactive command-line applications, processing data, or working with files, a solid understanding of Python’s input and output (I/O) mechanisms is crucial. At its core, input is how a program receives data, while output is how it presents results to the user.

This article is a practical guide to mastering these essential skills. This article provides 20+ Python Input and Output practice questions that focus entirely on taking user input, displaying information, and interacting with files. You will also learn techniques for formatting output to present your data clearly and in a user-friendly way.

Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.

  • All solutions have been fully tested on Python 3.
  • Interactive Learning: Use our Online Code Editor to solve these exercises in real time.

Also Read:

  • Python Exercises: A set of 20 topic-specific exercises
  • Python input and Output
  • Python File Handling
  • Python Input and Output Quiz
+ Table of Contents (23 Exercises)

Table of contents

  • Exercise 1. Accept numbers from a user
  • Exercise 2. Display variables with a separator
  • Exercise 3. Convert decimal number to octal
  • Exercise 4. Binary representation
  • Exercise 5. Accept any three strings from one input() call
  • Exercise 6. Hexadecimal representation
  • Exercise 7. Display float number with 2 decimal places
  • Exercise 8. Percentage display
  • Exercise 9: Display right-aligned output
  • Exercise 10. Center-aligned text
  • Exercise 11: Padding with zeros
  • Exercise 12: Format variables using string.format() method
  • Exercise 13. Currency formatting with commas
  • Exercise 14: Accept a list of 5 float numbers
  • Exercise 15. Tabular output from lists
  • Exercise 16. Interactive menu
  • Exercise 17. Masked password input ( getpass )
  • Exercise 18. Read a file and store its content in a list
  • Exercise 19. Write list of strings to a file
  • Exercise 20. Count total lines in a file
  • Exercise 21. Read line number 4 from a file
  • Exercise 22. Check if file is empty
  • Exercise 23. Delete a specific file

Exercise 1. Accept numbers from a user

Practice Problem: Write a program that accepts two integer numbers from the user and calculates their multiplication. Print the final result to the console.

Exercise Purpose: This exercise introduces the fundamental concept of user interaction. It teaches how to use the input() function to capture data and the importance of “type casting” (converting strings to integers) since all input starts as text.

Given Input:

  • First Number: 10
  • Second Number: 20

Expected Output: The multiplication is: 200

Help: Take user input in Python

Hint

The input() function always returns a string. You must wrap it in int() before performing mathematical operations.

Solution
# Accept input from user
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))

# Calculate multiplication
res = num1 * num2

# Display result
print("The multiplication is:", res)Code language: Python (python)

Explanation to Solution:

  • int(input(...)): This nested function call takes the user’s keystrokes and immediately transforms them into a whole number (integer) so Python can do math with them.
  • num1 * num2: The asterisk is the multiplication operator in Python.
  • print(): This function outputs the final calculated value to the screen.

Exercise 2. Display variables with a separator

Practice Problem: Use the print() function to format the words “Name”, “Is”, and “James” so they appear with three asterisks (***) between them.

Exercise Purpose: The print() function is more powerful than it looks. This exercise teaches the use of the sep (separator) keyword argument, which allows you to define how multiple items should be joined together in the output without manually typing strings.

Given Input:

  • Strings: “Name”, “Is”, “James”

Expected Output:

Name***Is***James
Hint

You can pass multiple arguments to print() separated by commas, then use the sep parameter at the end to define the connector.

Solution
# Using the sep parameter to join strings
print('Name', 'Is', 'James', sep='***')Code language: Python (python)

Explanation to Solution:

  • Comma Separation: In Python’s print(), commas signify different objects to be printed.
  • sep='***': By default, sep is a space. By changing it to '***', we tell Python to place that specific string between every object listed in the function call.

Exercise 3. Convert decimal number to octal

Practice Problem: Accept an integer from the user and display it as an octal number (Base 8).

Exercise Purpose: Computers often use different numbering systems (Hexadecimal, Octal, Binary). This exercise demonstrates how to use “Format Specifiers” in strings to automatically convert values between number systems for display.

Given Input: Decimal: 8

Expected Output:

The octal number of decimal number 8 is 10
Hint

Use the %o format specifier inside a string or the oct() function. To match the specific output format, %o is often the cleanest method.

Solution
num = 8
# Using %o to format the integer as octal
print('%o' % num)Code language: Python (python)

Explanation to Solution:

  • %o: This is a placeholder that tells Python: “Take the integer provided and represent it as an Octal value.”
  • Base-8 Logic: In Octal, the number 8 is represented as 10 because the system “rolls over” after 7.

Exercise 4. Binary representation

Practice Problem: Accept an integer from the user and display its value in binary format (Base 2).

Exercise Purpose: Computers process everything in binary. This exercise shows how to use Python’s built-in formatting to visualize how a decimal number is represented at the hardware level using only 0s and 1s.

Given Input: Decimal Number: 45

Expected Output:

The binary representation of 45 is 101101
Hint
  • You can use the bin() function or the :b format specifier inside an f-string.
  • Using the f-string method allows you to omit the 0b prefix that bin() usually adds.
Solution
num = int(input("Enter a decimal number: "))

# Using f-string with the 'b' (binary) type code
binary_val = f"{num:b}"

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

Explanation to Solution:

  • :b: This is the binary type code. It tells Python to convert the integer into its Base-2 equivalent.
  • Base-2 Logic: In binary, 45 is calculated as ( 32 * 1 ) + ( 16 * 0 ) + ( 8 * 1 ) + ( 4 * 1 ) + ( 2 * 0) + ( 1 * 1)

Exercise 5. Accept any three strings from one input() call

Practice Problem: Write a program that takes three names (or any words) from a user in a single input prompt and assigns them to three separate variables.

Exercise Purpose: Users dislike having to hit Enter three times for three pieces of data. This exercise teaches the split() method, the standard way to parse a single string into multiple data points based on whitespace.

Given Input: Emma Jessa Kelly

Expected Output:

Name1: Emma
Name2: Jessa
Name3: Kelly
Hint

Use the split() function on the result of input(). This will turn the single string into a list of words.

Solution
# Taking multiple inputs in one go
str1, str2, str3 = input("Enter three names: ").split()

print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)Code language: Python (python)

Explanation to Solution:

  • .split(): By default, this function looks for spaces and “splits” the string there.
  • Unpacking: The syntax str1, str2, str3 = ... is called “iterable unpacking.” It takes the resulting list of three items and distributes them into the three variables in order.

Exercise 6. Hexadecimal representation

Practice Problem: Accept an integer and display its value in hexadecimal format (Base 16).

Exercise Purpose: Hexadecimal is widely used in computing for memory addresses and color codes (e.g., #FFFFFF). This exercise teaches you how to bridge the gap between human-readable decimals and developer-centric hex values.

Given Input: Decimal Number: 255

Expected Output: The hexadecimal value is ff

Hint

Use the :x specifier for lowercase hex or :X for uppercase hex within an f-string.

Solution
num = int(input("Enter a number: "))

# :x produces lowercase (ff), :X produces uppercase (FF)
hex_val = f"{num:x}"

print(f"The hexadecimal value is {hex_val}")Code language: Python (python)

Explanation to Solution:

  • :x: The hexadecimal type code. Hex uses sixteen symbols: 0–9 and a–f.
  • Case Sensitivity: Using lowercase x results in ff, while uppercase X would result in FF. This is a common requirement in protocol documentation.

Exercise 7. Display float number with 2 decimal places

Practice Problem: Display a float number (a number with decimals) such as 458.541315 rounded to exactly two decimal places.

Exercise Purpose: Real-world data can be messy. This task is important for UI/UX and reporting because it helps make long, complex floating-point numbers easier to read.

Given Input: Number: 458.541315

Expected Output: 458.54

Hint

You can use the %.2f format specifier or the format() function to limit the precision of a floating-point number.

Solution
num = 458.541315

# Displaying 2 decimal places using formatting
print('%.2f' % num)Code language: Python (python)

Explanation to Solution:

  • %.2f: The f stands for “float,” and the .2 tells Python to stop after two digits following the decimal point.
  • Rounding: Python automatically rounds the last digit appropriately when using this formatting method.

Exercise 8. Percentage display

Practice Problem: Ask the user for a numerator and a denominator. Calculate the percentage (numerator/denominator * 100) and display it with exactly two decimal places followed by a percent sign.

Exercise Purpose: In this exercise, you will learn about string interpolation. You will practice combining math results with symbols like % and learn how to control the number of decimal places so your answers look neat.

Given Input:

  • Numerator: 22
  • Denominator: 29

Expected Output: The result is: 75.86%

Hint
  • Use an f-string or the format() method with the .2f specifier.
  • Remember to multiply by 100 first to get the percentage value!
Solution
num = int(input("Enter numerator: "))
den = int(input("Enter denominator: "))

percentage = (num / den) * 100

# Using f-string for precision and adding the '%' literal
print(f"The result is: {percentage:.2f}%")Code language: Python (python)

Explanation to Solution:

  • percentage:.2f: Inside the curly braces of an f-string, the :.2f part tells Python to format the number as a float with two digits after the decimal point.
  • The trailing %: Since the percent sign isn’t a special character in f-strings (unlike in the old % formatting style), you can just type it at the end of the curly brace.

Exercise 9: Display right-aligned output

Practice Problem: Ask the user for a word and a number. Print the word right-aligned in a total field width of 20 characters, followed by the number.

Exercise Purpose: Good design is important. When you create text-based reports, lining up columns makes them easier to read. In this exercise, you will learn how to use Alignment Flags to set aside space on the screen and move text to the left, right, or center.

Given Input:

  • Word: “Python”
  • Number: 3.12

Expected Output:

               Python 3.14
Hint

In an f-string, you can use the > symbol followed by a number (like :>20) to right-align text.

Solution
word = input("Enter a word: ")
version = input("Enter a version number: ")

# Right-align the word in 20 spaces
print(f"{word:>20} {version}")Code language: Python (python)

Explanation to Solution:

  • :>20: This tells Python, “Reserve a block of 20 characters. Put the variable at the very end (right) and fill the remaining space on the left with blanks.”
  • Padding: If the word is “Python” (6 letters), Python will automatically insert 14 spaces before it.

Exercise 10. Center-aligned text

Practice Problem: Display a string centered within a 40-character field, using hyphens (-) as the padding character.

Exercise Purpose: Centering text is a common way to make headers or dividers in console reports. In this exercise, you will learn about the “Fill” and “Align” parts of f-string formatting.

Given Input: Text: “REPORT SUMMARY”

Expected Output:

-------------REPORT SUMMARY-------------
Hint

The syntax for centering with a fill character is :{char}^{width}.

Solution
title = "REPORT SUMMARY"

# Center (^) with hyphen (-) as fill in a width of 40
formatted_title = f"{title:-^40}"

print(formatted_title)Code language: Python (python)

Explanation to Solution:

  • -: The character used to fill the empty space.
  • ^: The alignment flag for “Center.”
  • 40: The total width of the resulting string. Python calculates how many hyphens are needed on each side to make the total length exactly 40.

Exercise 11: Padding with zeros

Practice Problem: Ask the user for a number. Print this number padded with leading zeros so the total width is exactly 5 digits.

Exercise Purpose: This method is important when you need to create standardized IDs, serial numbers, or digital clock displays, such as showing “09” instead of “9” minutes. It shows you how to set a specific number format no matter the original input size.

Given Input: Number: 42

Expected Output: 00042

Hint

You can use the zfill() string method or the :05 f-string format specifier.

Solution
val = input("Enter your ID number: ")

# Method 1: Using zfill
print(val.zfill(5))

# Method 2: Using f-string (requires integer)
# print(f"{int(val):05}")Code language: Python (python)

Explanation to Solution:

  • zfill(5): This is a built-in string method specifically designed to add “0” characters to the start of a string until it reaches the desired length.
  • Use Case: This is incredibly common when naming files (e.g., image_001.jpg, image_002.jpg) so they sort correctly in your computer’s folders.

Exercise 12: Format variables using string.format() method

Practice Problem: Given three variables quantity = 3, totalMoney = 450, and price = 150, use the format() method to print a sentence that neatly displays these values.

Exercise Purpose: Hard-coding strings with plus signs (+) is messy and error-prone. This exercise introduces the .format() method, a powerful way to inject variables into templates with precision and readability.

Given Input: quantity = 3, totalMoney = 450, price = 150

Expected Output:

I have 450 dollars so I can buy 3 football for 150.00 dollars.
Hint
  • Place curly braces {} inside your string as placeholders.
  • Next, call .format() on that string and pass the variables in the order you want them to appear.
Solution
quantity = 3
totalMoney = 450
price = 150
statement = "I have {1} dollars so I can buy {0} football for {2:.2f} dollars."

print(statement.format(quantity, totalMoney, price))Code language: Python (python)

Explanation to Solution:

  • {0}, {1}, {2}: These numbers refer to the position of the arguments in the .format() call. This allows you to reuse variables or change their order without rearranging the function call.
  • {2:.2f}: This is a bit of formatting magic that tells Python to treat the third variable as a float and show exactly two decimal places.

Exercise 13. Currency formatting with commas

Practice Problem: Display a large number as currency, including a dollar sign, commas for thousands, and two decimal places.

Exercise Purpose: Financial applications require strict formatting. This exercise combines three concepts: prefixing, grouping (using commas), and precision to create a professional-grade money display.

Given Input: Amount: 1250500.7

Expected Output:

Total Balance: $1,250,500.70
Hint
  • Use a comma within the format specifier to act as the thousands separator.
  • The full specifier would look something like :, .2f.
Solution
balance = 1250500.7

# , adds commas, .2f adds two decimal places
formatted_balance = f"${balance:,.2f}"

print(f"Total Balance: {formatted_balance}")Code language: Python (python)

Explanation to Solution:

  • ,: This special grouping character tells Python to insert a comma every three digits.
  • .2f: Ensures the cents are always shown as two digits (e.g., .70 instead of .7).
  • $: Simply a literal character placed outside the curly braces to denote the currency.

Exercise 14: Accept a list of 5 float numbers

Practice Problem: Write a program that accepts 5 float numbers as input from the user and stores them in a list.

Exercise Purpose: This exercise moves beyond single variables to “Data Structures.” It teaches how to use loops or list comprehension to efficiently handle multiple inputs and store them in a single list.

Given Input: Numbers: 78.6, 78.6, 85.3, 1.2, 3.5

Expected Output: [78.6, 78.6, 85.3, 1.2, 3.5]

Refer: Take a list as input in Python.

Hint

You can use a for loop that runs 5 times, each time appending the user’s input (converted to float) to an empty list.

Solution
numbers = []

# Run a loop 5 times to get 5 inputs
for i in range(0, 5):
    print("Enter number at location", i, ":")
    item = float(input())
    numbers.append(item)

print("User List:", numbers)Code language: Python (python)

Explanation to Solution:

  • numbers = []: Creates an empty container (list) to hold the data.
  • range(0, 5): Ensures the loop runs exactly five times.
  • float(input()): Similar to Exercise 1, but converts the input to a decimal-capable “float” instead of an integer.
  • .append(item): This method adds the new number to the end of the existing list.

Exercise 15. Tabular output from lists

Practice Problem: You have two lists: names = ["Alice", "Bob", "Charlie"] and scores = [85, 92, 78]. Print these as a table with aligned columns.

Exercise Purpose: This exercise introduces “Parallel Iteration.” It teaches you how to step through two related lists simultaneously and format them to look like an organized database table.

Given Input:

  • names = ["Alice", "Bob", "Charlie"]
  • scores = [85, 92, 78]

Expected Output:

Name       Score
----------------
Alice 85
Bob 92
Charlie 78
Hint
  • Use the zip() function to loop through both lists simultaneously.
  • Use fixed-width formatting (like :<10) to keep the columns straight.
Solution
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

print(f"{'Name':<10} {'Score'}")
print("-" * 15)

for name, score in zip(names, scores):
    print(f"{name:<10} {score}")Code language: Python (python)

Explanation to Solution:

  • zip(names, scores): This “zips” the two lists together like a zipper, pairing “Alice” with 85, “Bob” with 92, and so on.
  • :<10: This is the “left-align” flag. It ensures the Name column is always 10 characters wide, so the Score column always starts at the exact same horizontal position.

Exercise 16. Interactive menu

Practice Problem: Create a menu that offers three options: “1. Say Hello”, “2. Calculate Square”, and “3. Exit”. The program should perform the action based on the number the user types.

Exercise Purpose: This is the foundation of “Command Line Interfaces” (CLI). It teaches you how to map user input to specific logic blocks using conditional statements, turning a linear script into an interactive application.

Given Input:

  • Choice: 2
  • Number to square: 5

Expected Output:

Enter choice (1-3): 2
Enter number to square: 5
The square is: 25
Hint
  • Use an if-elif-else structure to catch the user’s choice.
  • Always include an else to handle “invalid” inputs like someone typing “9”.
Solution
print("1. Say Hello\n2. Calculate Square\n3. Exit")
choice = input("Enter choice (1-3): ")

if choice == "1":
    print("Hello there! Hope you're having a great day.")
elif choice == "2":
    val = int(input("Enter number to square: "))
    print(f"The square is: {val * val}")
elif choice == "3":
    print("Exiting... Goodbye!")
else:
    print("Invalid choice. Please pick 1, 2, or 3.")Code language: Python (python)

Explanation to Solution:

  • String Comparison: Notice we compare choice == "1". Since input() returns a string, we don’t even need to convert it to an integer unless we plan to do math with the choice itself.
  • Control Flow: The elif (else-if) ensures that only one block of code runs, skipping the others once a match is found.

Exercise 17. Masked password input (getpass)

Practice Problem: Write a script that asks a user for their username using standard input and their password using masked input (where the characters don’t appear on the screen).

Exercise Purpose: Security is paramount. Using input() for passwords is a major vulnerability because the password remains visible in the terminal’s scrollback buffer. The getpass module is the standard way to handle sensitive credentials by suppressing local echo.

Given Input:

  • Username: admin
  • Password: SecretPassword123 (invisible during typing)

Expected Output:

Enter Username: admin
Password:
Login successful for admin!
Hint

You need to import getpass. Use getpass.getpass() instead of input() for the sensitive field.

Solution
import getpass

user = input("Enter Username: ")
# Characters will not be displayed as you type
pwd = getpass.getpass("Password: ")

if user == "admin" and pwd == "SecretPassword123":
    print(f"Login successful for {user}!")
else:
    print("Access Denied.")Code language: Python (python)

Explanation to Solution:

  • import getpass: This is a standard Python library designed specifically for secure interaction.
  • getpass.getpass(): This function talks directly to the terminal to turn off “echoing.” While the user types, the cursor stays still, and no characters are sent to the display.
  • Logic: Despite being hidden from the screen, the variable pwd still stores the exact string the user typed for comparison.

Exercise 18. Read a file and store its content in a list

Practice Problem: Read an existing file test.txt and store every line as an individual element in a Python list.

Exercise Purpose: It’s the first step in “Data Parsing”, taking raw text from a disk and converting it into a structured format (a list) that Python can easily sort, filter, or search.

Given Input: A file test.txt with multiple lines.

Expected Output: ['Line 1', 'Line', 'Line']

See:

  • Python file handling
  • Python Read file
Hint

Use the readlines() method, which automatically reads the entire file and breaks it into a list based on the newline characters.

Solution
# Read file content into a list
with open("test.txt", "r") as f:
    lines = f.readlines()
    print(lines)Code language: Python (python)

Explanation to Solution:

  • readlines(): This is a memory-efficient way to capture the entire structure of a file.
  • \n in Output: You will notice the newline characters are preserved in the list. To remove them, you would typically use a list comprehension with .strip().

Exercise 19. Write list of strings to a file

Practice Problem: Take a list of favorite fruits and save each fruit onto a new line in a file named fruits.txt.

Exercise Purpose: In data science or web dev, you often process data in memory (as a list) and then need to “persist” it (save it to a disk). This exercise teaches you how to export structured Python data into a permanent text format.

Given Input:

  • fruit_list = ["Apple", "Banana", "Cherry", "Date"]

Expected Output: A file fruits.txt created with each fruit on its own line.

Help: Python write file

Hint
  • Use the with open() statement in "w" (write) mode.
  • Remember to add a newline character \n to each string, or the list will be squashed into a single line.
Solution
fruit_list = ["Apple", "Banana", "Cherry", "Date"]

# Open file for writing
with open("fruits.txt", "w") as f:
    for fruit in fruit_list:
        f.write(fruit + "\n")

print("File 'fruits.txt' has been created successfully.")Code language: Python (python)

Explanation to Solution:

  • with open(...) as f: This is the “Context Manager.” It handles opening and closing the file stream, ensuring no memory leaks occur even if the code fails midway.
  • "w" mode: This stands for “write.” Be careful: it will completely overwrite the file if it already exists.
  • + "\n": Files are just long streams of characters. We manually add the “New Line” character to ensure the file is human-readable.

Exercise 20. Count total lines in a file

Practice Problem: Write a program that opens an existing text file and calculates exactly how many lines of text it contains.

Exercise Purpose: This is a fundamental “Data Auditing” task. Before you process a log file or a dataset, you need to know its size. This exercise teaches you how to iterate through a file object efficiently.

Given Input: A file sample.txt with 12 lines of text.

Expected Output: 12

Hint

You can use a simple counter inside a for loop that iterates over the file object. Python treats a file object as a “generator” of lines.

Solution
line_count = 0

with open("sample.txt", "r") as f:
    for line in f:
        line_count += 1

print(f"The file contains {line_count} lines.")Code language: Python (python)

Explanation to Solution:

  • Memory Efficiency: Instead of using f.readlines() (which loads the entire file into RAM), for line in f reads one line at a time. This allows you to count lines in a 10GB file without crashing your computer.
  • The Counter: Every time the loop completes one cycle, it means it found a newline character, so we increment line_count.

Exercise 21. Read line number 4 from a file

Practice Problem: Open a file and display only the fourth line of the content.

Exercise Purpose: Sometimes files are massive (gigabytes in size), and you only need a specific snippet. This exercise reinforces the idea that file lines can be treated like a list, allowing for direct, indexed access.

Given Input: A file test.txt containing:

Line 1
Line 2
Line 3
Line 4
Line 5

Expected Output: Line 4

See: Read Specific Lines From a File in Python

Hint

Use readlines() to get a list of all lines, then access the index 3.

Solution
# Opening the file in read mode
with open("test.txt", "r") as f:
    # Read all lines into a list
    lines = f.readlines()
    # Print the 4th line (index 3)
    print(lines[3])Code language: Python (python)

Explanation to Solution:

  • readlines(): Once again, this creates a list where each element is one line of text.
  • lines[3]: Because Python is zero-indexed, the first line is at index 0, the second at index 1, and so on. Therefore, line 4 is found at index 3.

Exercise 22. Check if file is empty

Practice Problem: Write a script that checks a file’s metadata. If the file size is 0 bytes, print “File is empty”; otherwise, print the size in bytes.

Exercise Purpose: Sometimes a file exists but contains no data (common in failed downloads or interrupted logs). This exercise introduces the os module and “system metadata”—information about a file rather than the content inside it.

Given Input: An empty file named empty_log.txt.

Expected Output:

Checking empty_log.txt...
Status: File is empty.
Hint

You will need to import os and use os.stat("filename").st_size.

Solution
import os

filename = "empty_log.txt"

# Check if the file actually exists first to avoid errors
if os.path.exists(filename):
    file_info = os.stat(filename)
    if file_info.st_size == 0:
        print(f"Status: {filename} is empty.")
    else:
        print(f"Status: {filename} size is {file_info.st_size} bytes.")
else:
    print("File not found.")Code language: Python (python)

Explanation to Solution:

  • os.stat(): This function performs a “system call” to the Operating System to retrieve a structure of information (size, creation date, permissions).
  • .st_size: This specific attribute tells you the size in bytes. 1 byte usually equals one character.
  • os.path.exists(): A defensive programming practice that prevents your script from crashing if the file is missing.

Exercise 23. Delete a specific file

Practice Problem: Write a program that asks the user for a filename and deletes it from the folder. Caution: This operation is permanent.

Exercise Purpose: File system maintenance. This exercise shows you how Python can perform high-level administrative tasks. It also emphasizes the importance of “High Risk” operations and the need to always verify the user’s intent.

Given Input: Filename to delete: old_data.csv

Expected Output:

Are you sure you want to delete 'old_data.csv'? (y/n): y
File 'old_data.csv' has been deleted.
Hint

Use os.remove(). Always wrap this in a condition to check if the file exists first, or Python will throw an FileNotFoundError.

Solution
import os

target = input("Enter filename to delete: ")

if os.path.exists(target):
    confirm = input(f"Are you sure you want to delete '{target}'? (y/n): ")
    if confirm.lower() == 'y':
        os.remove(target)
        print(f"File '{target}' has been deleted.")
    else:
        print("Operation cancelled.")
else:
    print("Error: File does not exist.")Code language: Python (python)

Explanation to Solution:

  • os.remove(): This is the core command that tells the OS to un-link the file from the directory. There is no “Recycle Bin” for this command; it is gone immediately.
  • .lower() == 'y': This makes your user interface more robust by accepting “Y” or “y”.
  • Defensive Logic: By checking os.path.exists(), you ensure the program handles missing files gracefully rather than stopping with a red error message.

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

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