Input-Output Python Exercises with Solution

Input Output Python Exercises: input()  method is used to accept the values from the user in Python. input() and print() methods together used to accept input from the user using print() we can print output on the screen.

In this guide, we’ll also solve programming exercises in python related to File Handling (reading, writing, deleting and appending data to files). These programming exercise aims to help developers to learn and understand the concept of input() and print() also concepts of file handling much better. Without wasting more time, let’s get started.

python exercises with solution

Input Output Python Exercises:

We will solve 10 input output programming exercises in python with solution & detailed code explanation.

Exercise 1: Accept two numbers from the user and return their sum, multiplication and division.

Hint
Input:
a = 30
b = 10

Expected Output:
Sum is 40
Multiplication is 300
Division is 3

a = int(input("a = "))
b = int(input("b = "))

sum = a+b
mul = a*b
div = a/b

print("Sum is", sum)
print("Multiplication is", mul)
print("Division is", div)

Exercise 2: Write all the contents of a given file to new file.

Step 1:
Read data from a text file demo.txt
Step 2:
Write data of demo.txt file to new.txt file
Step 3:
Display the data written in the new file.

# reading data from demo file
f = open("demo.txt",'r')
z = f.read()
print("Data in demo.txt file")
print(z)

# writing data to new file
f = open("new.txt",'w')
f.write(z)

# reading data from new file
f = open("new.txt",'r')
z = f.read()
print("\nData in new.txt file")
print(z)

Explanation:

  • #reading data from demo file: Here in this section, we are reading data from a demo.txt file. We opened the file in read mode and using the read() method we initialized all the contents of file to variable z. In the next line, we printed the data.
  • #writing data to demo file: Here in this section, we are writing data that we read from the demo.txt file to the new.txt file. We opened the new.txt file in write mode and using the write() method we have written the data to the new.txt file.
  • #reading data from new file: This section is the same as that of the first section. In this section we are reading the contents of the new.txt file. Just to confirm whether the data is written to the file successfully or not.
    input output exercises in python with solution

Exercise 3: Read all the data from the text file except line number 5.

Step 1:
Read data from a text file demo.txt
Step 2:
Use for loop for iteration on each line
Step 3:
Display the data skipping the 5th line

#Reading all data of file
def read_data():
    f = open("demo.txt",'r')
    s = f.readlines()
    for i in range(len(s)):
        print(s[i])
read_data()

#Reading all lines except line 5
def read_data():
    f = open("demo.txt",'r')
    s = f.readlines()
    for i in range(len(s)):
        if i == 4:
            pass
        else:
            print(s[i])
read_data()

Explanation:

  • Note: Must have text file ‘demo.txt’.
  • We have defined the first method to know what contents and how many lines our text file contains.
  • #Reading all data of file: In this section, we have read all the contents of file demo.txt and printed successfully using for loop.
  • #Reading all lines except line 5: In this section, we did some modification in our function during the iteration of for loop. When the value of i reaches index 4 (index starts from 0), we used the pass keyword. Hence when the index reaches 5, instead of printing the line it will pass or skip that particular line. Hence, the fifth line is skipped.
    # OUTPUT
    # Hi everyone, I hope you are doing good.
    # Welcome to PythonLobby Tutorials
    # Learn by code.
    # Machine Learning.
    # Data Analysis.
    # www.pythonlobby.com
    
    # Hi everyone, I hope you are doing good.
    # Welcome to PythonLobby Tutorials
    # Learn by code.
    # Machine Learning.
    # www.pythonlobby.com
    

Exercise 4: Accept three input values from the user in one input() call.

Hint
Input:
Enter three values: adam watson winslet

Expected Output:
Result is: adam watson winslet

# Getting three value inputs in single call

val1, val2, val3 = input("Enter three values ").split()
print(val1, val2, val3)

# output
# Result is: adam watson winslet

Exercise 5: Accept input from the user and display the occurrence of that specific word from a text file.

Hint
Input:
Enter the word to count: Learn

Expected Output:
Result is: 2

# Counting the occurrence of specific word
def read_data():
x = input("Enter the word you wan to count")
f = open("demo.txt",'r')
s = f.read()
s = s.split()
count = 0
for i in range(len(s)):
if s[i] == x:
count = count+1
else:
pass
print(count)

read_data()

# output
# Enter the word you wan to count: Learn
# 2

Explanation:

  • We have defined a function read() to count the occurrence of a word in a text file.
  • In the first line, first we have taken the input from the user that the user wants to count.
  • In the next line, we opened the file in read mode and split the whole text so that each word will get separated from each other w.r.t space.
  • Now we set the counter to 0 and start the execution of for loop till the length of s.
  • If the word that matches with the user input occurs, then the counter will increment by 1.
  • Hence at last we got the final result.

Exercise 6: Read a file and return the count of letters in a text file.

Expected Output
Total letters are 138

# Count of letters in text file

def read_data():
    f = open("demo.txt",'r')
    s = f.read().strip()
    count = 0
    for i in s:
        count = count+1
    print("Total letters are",count)

read_data()

# output
# Total letters are 138

Explanation:

  • We have defined a function read_data() to count the occurrence of the letter in a text file.
  • In the first line, we opened the text file in reading mode.
  • Next, we initialized the variable s with the data read from the text file. Here strip() function is used to remove the blank spaces.
  • We initialized the count=0 variable to use it as a counter.
  • Now we used for loop to iterate over each data that has stored in variable s.
  • Hence this way we can count the letters available in a text file.

Exercise 7: Read a file and return the count of words in a text file.

Expected Output:
Total words are 20

# Count of words in text file

def read_data():
    f = open("demo.txt",'r')
    s = f.read().split()
    count = 0
    for i in s:
        count = count+1
    print("Total words are",count)

read_data()

# output
# Total words are 20

Explanation:

  • We have defined a function read_data() to count the occurrence of the letter in a text file.
  • In the first line, we opened the text file in reading mode.
  • Next, we initialized the variable s with the data read from the text file. Here the split() function is used to separate each word by blank spaces.
  • We initialized the count=0 variable to use it as a counter.
  • Now we used for loop to iterate over each word that has stored in variable s.
  • Hence this way we can count the words available in a text file.

Exercise 8: Read a file and check whether the word exists in a text file or not.

Expected Output:
Enter the word to count: Learn
Learn occurs 2 time

# Count of words in text file

def read_data():
    f = open("demo.txt",'r')
    s = f.read().split()
    count = 0
    x = input("Enter the word to count: ")
    for i in range(len(s)):
        if s[i] == x:
            count = count+1
    print(f"{x} occurs {count} times")

read_data()

# output
# Learn occurs 2 time

Explanation:

  • We have defined a function read_data() to count the occurrence of a specific word in a text file.
  • In the first line, we opened the text file in reading mode.
  • Next, we initialized the variable s with the data read from the text file. Here the split() function is used to separate each word by blank spaces.
  • We initialized the count=0 variable to use it as a counter. Also taking the input from the user and storing it in variable x.
  • Now we used for loop to iterate over each word that has stored in variable s.
  • Next, we used the if condition, if the word occurs in a file during iteration the count increment by 1.
  • Hence this way we can count the occurrence of a specific word in a text file.

Exercise 9: Write a program to Insert multiple data into a list.

Hint

Input:
Number of data to enter: 2
Data at index 1: 200
Data at index 2: PythonLobby

Expected Output:
[‘200′,’PythonLobby’]

# Entering data
n = int(input("How many data you want to enter: "))
l = []
for i in range(n):
    x= input(f"Data at index {i+1}: ")
    l.append(x)

# list after data insertion
print(l)

# output
# ['200','PythonLobby']

Exercise 10: Write a program to rename a text file in Python.

Hint

Read data from demo.txt file
Open a new file temp.txt in read mode
Write data of demo.txt file to temp.txt file
Delete the demo.txt file
Rename the temp.txt file to demo.txt

# Rename a text file
import os

def read_data():
    f = open("demo.txt",'r')
    s = f.read()
    f.close()
    f_new = open("temp.txt", 'w')
    f_new.write(s)
    f_new.close()
    os.remove("demo.txt")
    os.rename("temp.txt","demo.txt")

read_data()

Explanation:

  • Approach -> Our approach is to read a file demo.txt and store all of its content in a variable say s.
  • Next, we opened a new file temp.txt in write mode and wrote it with the data stored in variable s that we have read from our demo.txt file.
  • Now both temp.txt and demo.txt file have the same data.
  • Finally, we delete the demo.txt file using the os module of python and in the very next line, we renamed the temp.txt file with the demo.txt file.
  • Hence we successfully renamed the text file without affecting its data.