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
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
Explanation to Solution:
- Comma Separation: In Python’s
print(), commas signify different objects to be printed. sep='***': By default,sepis 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
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
10because 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:bformat specifier inside an f-string. - Using the f-string method allows you to omit the
0bprefix thatbin()usually adds.
Solution
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
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
Explanation to Solution:
:x: The hexadecimal type code. Hex uses sixteen symbols: 0–9 and a–f.- Case Sensitivity: Using lowercase
xresults inff, while uppercaseXwould result inFF. 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
Explanation to Solution:
%.2f: Thefstands for “float,” and the.2tells 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.2fspecifier. - Remember to multiply by 100 first to get the percentage value!
Solution
Explanation to Solution:
percentage:.2f: Inside the curly braces of an f-string, the:.2fpart 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
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
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
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
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
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.,.70instead 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
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
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-elsestructure to catch the user’s choice. - Always include an
elseto handle “invalid” inputs like someone typing “9”.
Solution
Explanation to Solution:
- String Comparison: Notice we compare
choice == "1". Sinceinput()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
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
pwdstill 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:
Hint
Use the readlines() method, which automatically reads the entire file and breaks it into a list based on the newline characters.
Solution
Explanation to Solution:
readlines(): This is a memory-efficient way to capture the entire structure of a file.\nin 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
\nto each string, or the list will be squashed into a single line.
Solution
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
Explanation to Solution:
- Memory Efficiency: Instead of using
f.readlines()(which loads the entire file into RAM),for line in freads 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
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
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
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.
