[Python] – Input/Output Exercise

by | Jan 24, 2024 | Ngôn ngữ lập trình, Python | 0 comments

Exercise 1: Accept numbers from a user

Write a program to accept two numbers from the user and calculate multiplication

Hint:

  • Use Python 3’s built-in function input() to accept user input
  • Convert user input to the integer type using the int() constructor.

Solution

num1 = int(input("Enter first number "))
num2 = int(input("Enter second number "))
res = num1 * num2
print("Multiplication is", res)

Exercise 2: Display string as template

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

Expected Output:

Name**Is**James

Hint:

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

Solution:

print('My', 'Name', 'Is', 'James', sep='**')

Exercise 3: Convert number base using print() and output formatting

Convert a number from decimal to octal using print() with output formatting.

Example Input:

num = 8

Expected Output:

The octal number of decimal number 8 is 10

Hint:

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

Solution:

num = 8
print('The octal number of decimal number 8 %o' % num)

Exercise 4: Display float number with 2 decimal places

Display float number with 2 decimal places using print()

Example Input:

num = 458.541315

Expected Output:

458.54

Hint:

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

Solution:

num = 458.541315
print('%.2f' % num)

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

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

Expected Output:

[78.6, 78.6, 85.3, 1.2, 3.5]

Hint:

  • Create a list variable named numbers
  • Run loop five times
  • In each iteration of the loop, use the input() function to take input from a user
  • Convert user input to float number using the float() constructor
  • Add float number to the numbers list using the append() function

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)

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

Write all content of a given file into a new file by skipping line number X.

Create a test.txt file and add the below content to the left col. If we skipping line number 5, the output is the right col.

line1
line2
line3
line4
line5
line6
line7
line1
line2
line3
line4
line6
line7

Hint:

  • Read all lines from a test.txt file using the readlines() method. This method returns all lines from a file as a list
  • Open new text file in write mode (w)
  • Set counter = 0
  • Iterate each line from a list
  • if the counter is 4, skip that line, else write that line in a new text file using the write() method
  • Increment counter by 1 in each iteration

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 = 1
    # iterate each lines from a test.txt
    for line in lines:
        # skip 5th lines
        if count != 5:
            continue
        # write current line
        fp.write(line)
        # in each iteration reduce the count
        count += 1

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

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

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

Expect Ouput:

Enter three string Emma Jessa Kelly
Name1: Emma
Name2: Jessa
Name3: Kelly

Solution:

str1, str2, str3 = input("Enter three string").split()
print('Name1:', str1)
print('Name2:', str2)
print('Name3:', str3)

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

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

Example:

totalMoney = 1000
quantity = 3
price = 450
I have 1000 dollars so I can buy 3 football for 450.00 dollars.

Hint:

Use the formatting code in print() function to print paragraph by pre format string.

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))

Exercise 9: Check file is empty or not

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

Hint:

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

Solution:

import os

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

Exercise 10: Read line number x from the following file

Write a python program to:

Accept an input as a number X

Open test.txt file and read the content at line number X.

test.txt:

line1
line2
line3
line4
line5
line6
line7

Solution:

x = int(input("Input index of line to pick out: "))
# read file
with open("test.txt", "r") as fp:
    # read all lines from a file
    lines = fp.readlines()
    # get line number 3
    print(lines[x])