PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python Exercises » Python Input and Output Exercise

Python Input and Output Exercise

Updated on: June 8, 2025 | 111 Comments

Whether you’re building interactive command-line applications, processing user data, or working with files, a solid understanding of Python’s input and output mechanisms is crucial.

  • Input: how a program receives data
  • Output: how it presents results.

This article serves as a practical guide to enhancing your skills in this essential area.

Through a series of 15 coding questions on basic I/O operations, you’ll practice and solidify your understanding of taking user input, displaying information effectively, and interacting with files.

Furthermore, you’ll be able to practice various techniques for formatting output to present data in a clear and user-friendly manner.

Let us know if you have any alternative solutions. Your insights will help other developers.

Also Read:

  • Python Exercises: A set of 18 topic specific exercises
  • Python input and Output
  • Python File Handling
  • Python Input and Output Quiz

Use Online Code Editor to solve exercise questions.

Table of contents

  • Exercise 1: Accept Numbers From User
  • Exercise 2: Format Output String
  • Exercise 3: Display Decimal Number to Octal using print() function
  • Exercise 4: Display Float Number with 2 Decimal Places
  • Exercise 5: Accept a list of 5 float numbers as an input from the user
  • Exercise 6: Write all content of a file into a new file by skipping line number 5
  • Exercise 7: Accept any three string from one input() call
  • Exercise 8: Format variables using string.format() method
  • Exercise 9: Check File is Empty or Not
  • Exercise 10: Read Line Number 4 from File
  • Exercise 11: Percentage Display
  • Exercise 12: Interactive Menu
  • Exercise 13: Display Right-Aligned Output
  • Exercise 14: Tabular Output from Lists
  • Exercise 15: Padding with Zeros

Exercise 1: Accept Numbers From User

Write a program to accept two integer numbers from the user and calculate their product.

Help: Take user input in Python

Show Hint
  • Use Python 3’s built-in function input() to accept user input
  • Convert user input to the integer type using the int() constructor.
Show Solution
num1 = int(input("Enter first number "))
num2 = int(input("Enter second number "))

res = num1 * num2
print("Multiplication:", res)Code language: Python (python)

Exercise 2: Format Output String

Write a program to display four string “My, “Name“, “Is“, “James” as “My**Name**Is**James“.

Use the print() function to format the given words in the specified format. Display the ** separator between each string.

Given:

str1 = 'My'
str2 = 'Name'
str3 = 'Is'
str4 = 'James'Code language: Python (python)

Expected Output:

For example: print('your code') should display My**Name**Is**James

Show Hint

Use the sep parameter of the print() function to define the separator symbol between each word.

Show Solution
str1 = 'My'
str2 = 'Name'
str3 = 'Is'
str4 = 'James'
print(str1, str2, str3, str4, sep='**')Code language: Python (python)

Exercise 3: Display Decimal Number to Octal using print() function

Given:

num = 8Code language: Python (python)

Expected Output:

The octal representation of the decimal number 8 is 10.

Show Hint

Use the %o formatting code within the print() function to format a decimal number as octal.

Show Solution
num = 8
print('%o' % num)Code language: Python (python)

Exercise 4: Display Float Number with 2 Decimal Places

Given:

num = 458.541315Code language: Python (python)

Expected Output:

458.54
Show Hint

Use the %.2f formatting code within the print() function to format a float number to two decimal places

Show Solution
num = 458.541315
print('%.2f' % num)Code language: Python (python)

Exercise 5: Accept a list of 5 float numbers as an input from the user

Refer:

  • Take list as a input in Python.
  • Python list

Expected Output:

[78.6, 78.6, 85.3, 1.2, 3.5]

Show Hint
  • Create a list variable named numbers.
  • Run a loop five times. In each iteration of the loop, use the input() function to get input from the user.
  • Convert the user’s input to a floating-point number using the float() constructor.
  • Add the floating-point number to the numbers list using the append() function.
Show Solution
numbers = []

# 5 is the list size
# run loop 5 times
for i in range(0, 5):
    print("Enter number at location", i, ":")
    # accept float number from user
    item = float(input())
    # add it to the list
    numbers.append(item)

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

Exercise 6: Write all content of a file into a new file by skipping line number 5

See:

  • Python file handling
  • Python Read file
  • Python write file

Create a test.txt file and add the below content to it.

Given test.txt file:

line1
line2
line3
line4
line5
line6
line7

Expected Output: new_file.txt

line1
line2
line3
line4
line6
line7
Show Hint
  • Read all lines from the ‘test.txt’ file using the readlines() method.
  • This method returns all lines from a file as a list.
  • Open a new text file in write mode ('w').
  • Set counter = 0. Iterate through each line from the list.
  • If the counter is 4, skip that line; otherwise, write that line to the new text file using the write() method.
  • Increment counter by 1 in each iteration.
Show Solution
# read test.txt
with open("test.txt", "r") as fp:
    # read all lines from a file
    lines = fp.readlines()

# open new file in write mode
with open("new_file.txt", "w") as fp:
    count = 0
    # iterate each lines from a test.txt
    for line in lines:
        # skip 5th lines
        if count == 4:
            count += 1
            continue
        else:
            # write current line
            fp.write(line)
        # in each iteration reduce the count
        count += 1Code language: Python (python)

Exercise 7: Accept any three string from one input() call

Write a program to take three names as input from the user in a single call to the input() function.

See: Get multiple inputs from a user in one line

Show Hint
  • Ask the user to enter three names separated by space
  • Split input string on whitespace using the split() function to get three individual names

Expected Output

Enter three string Emma Jessa Kelly
Name1: Emma
Name2: Jessa
Name3: Kelly
Show Solution
str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)Code language: Python (python)

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

Write a program to use the string.format() method to format the following three variables according to the expected output.

Given:

totalMoney = 1000
quantity = 3
price = 450Code language: Python (python)

Expected Output:

I have 1000 dollars so I can buy 3 football for 450.00 dollars.
Show Solution
quantity = 3
totalMoney = 1000
price = 450
statement1 = "I have {1} dollars so I can buy {0} football for {2:.2f} dollars."
print(statement1.format(quantity, totalMoney, price))Code language: Python (python)

Exercise 9: Check File is Empty or Not

Write a program to check if the given file is empty or not

Show Hint

Use os.stat('file_name').st_size() function to get the file size. if it is 0 then the file is empty.

Show Solution
import os

size = os.stat("test.txt").st_size
if size == 0:
    print('file is empty')Code language: Python (python)

Exercise 10: Read Line Number 4 from File

See:

  • Read Specific Lines From a File in Python
  • Python read file

Create a test.txt file and add the below content to it.

test.txt file:

line1
line2
line3
line4
line5
line6
line7
Show Solution
# read file
with open("test.txt", "r") as fp:
    # read all lines from a file
    lines = fp.readlines()
    # get line number 3
    print(lines[2])Code language: Python (python)

Exercise 11: Percentage Display

Ask the user for a numerator and a denominator. Calculate the percentage and display it with two decimal places followed by a percent sign (e.g., 75.50%).

+ Show Hint
  • Get the numerator and denominator using input() function and convert them to floating-point numbers using float() function.
  • Calculate the percentage. Use an f-string with formatting specifiers to display the result with two decimal places and the percent sign
+ Show Solution

Steps to solve this question:

  • Split the given string into a list of words using the split() method
  • Use a list comprehension to create a new list by reversing each word from a list.
  • Use the join() function to convert the new list into a string
try:
    numerator = float(input("Enter the numerator: "))
    denominator = float(input("Enter the denominator: "))
    if denominator == 0:
        print("Error: Denominator cannot be zero.")
    else:
        percentage = (numerator / denominator) * 100
        print(f"The percentage is: {percentage:.2f}%")
except ValueError:
    print("Invalid input. Please enter numbers.")Code language: Python (python)

Exercise 12: Interactive Menu

Create a simple interactive menu with options like “1. Say Hello”, “2. Calculate Square”, “3. Exit”. Based on the user’s input, perform the corresponding action

+ Show Hint
  • Use a while loop to keep the menu running until the user chooses to exit.
  • Use input() to get the user’s choice and if-elif-else statements to perform the corresponding action.
+ Show Solution
while True:
    print("\nMenu:")
    print("1. Say Hello")
    print("2. Calculate Square")
    print("3. Exit")

    choice = input("Enter your choice (1-3): ")

    if choice == '1':
        print("Hello there!")
    elif choice == '2':
        try:
            number = int(input("Enter a number: "))
            square = number ** 2
            print(f"The square of {number} is {square}")
        except ValueError:
            print("Invalid input. Please enter an integer.")
    elif choice == '3':
        print("Exiting...")
        break
    else:
        print("Invalid choice. Please enter a number between 1 and 3.")Code language: Python (python)

Exercise 13: Display Right-Aligned Output

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

Expected Output:

Enter a word:  PYnative
Enter a number: 29
PYnative29
+ Show Hint

Use f-strings with the > alignment specifier and a width for the word. Then, simply print the number after it.

+ Show Solution
word = input("Enter a word: ")
number = input("Enter a number: ")
print(f"{word:>20}{number}")Code language: Python (python)

Exercise 14: Tabular Output from Lists

You have two lists: names = ["Alice", "Bob", "Charlie"] and scores = [85, 92, 78]. Print these lists as a simple table with columns “Name” and “Score”.

Expected Output:

Name       Score
---------------
Alice 85
Bob 92
Charlie 78
+ Show Hint
  • You’ll need to iterate through both lists simultaneously. You can use zip() to achieve this.
  • Then, use f-strings to format each row of the table.
+ Show Solution
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]

print(f"{'Name':<10} {'Score':<5}")
print("-" * 15)
for name, score in zip(names, scores):
    print(f"{name:<10} {score:<5}")Code language: Python (python)

Exercise 15: Padding with Zeros

Ask the user for a number. Print this number padded with leading zeros to a width of 5.

For example, if the input is 12, the output should be “00012“

+ Show Hint
  • Get the number as a string using input().
  • Use the zfill() string method to pad it with leading zeros to the desired width.
+ Show Solution
number_str = input("Enter a number: ")
padded_number = number_str.zfill(5)
print(padded_number)Code language: Python (python)

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

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 10 questions
  • Each Quiz contains 12-15 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
  • 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.

Explore Python

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

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

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–2025 pynative.com

Advertisement