Back to Python
2026-01-315 min read

Step 5: Follow the Instructions (Python Programming)

Learn Step 5: Follow the Instructions (Python Programming) step by step with clear examples and exercises.

Title: Step 5: Follow the Instructions (Python Programming)

Why This Matters

In programming, following instructions correctly is crucial. It's the foundation of writing error-free code and ensuring your programs work as intended. This lesson will guide you through a practical example that demonstrates the importance of following instructions in Python programming. By understanding and applying these concepts, you will develop good coding habits that will benefit you throughout your programming journey.

When programming, it's essential to follow the given instructions meticulously, especially when working on complex projects or collaborating with others. Following instructions correctly helps avoid bugs, saves time, and ensures that the final product meets its intended purpose. This lesson will help you understand how to follow instructions step-by-step, handle errors, and write clean, efficient code in Python.

Prerequisites

Before diving into this lesson, you should have a basic understanding of Python syntax, variables, data types, control structures such as if-else statements and loops, functions, exception handling, and file input/output (I/O). If you're not familiar with these concepts, consider reviewing them before proceeding:

Core Concept

In this example, we will create a simple Python program that reads a file line by line and performs a specific action on each line based on the instructions given in the file. The goal is to understand how to follow instructions step-by-step, handle errors, and write clean, efficient code in Python.

def process_file(filename):
with open(filename) as f:
for line in f:
instruction = line.strip()
if instruction == "SUM":
num1 = float(f.readline().strip())
num2 = float(f.readline().strip())
result = num1 + num2
print("The sum of", num1, "and", num2, "is", result)
elif instruction == "DIFF":
num1 = float(f.readline().strip())
num2 = float(f.readline().strip())
result = num1 - num2
print("The difference between", num1, "and", num2, "is", result)
elif instruction == "PROD":
num1 = float(f.readline().strip())
num2 = float(f.readline().strip())
result = num1 * num2
print("The product of", num1, "and", num2, "is", result)
elif instruction == "QUIT":
break
else:
print("Unknown instruction:", instruction)

Main function

if __name__ == "__main__":

process_file("instructions.txt")

How it works

  1. The process_file() function opens the specified file using the built-in open() function and a with statement, which ensures that the file is properly closed when the function finishes executing.
  2. The function iterates through each line in the file using a for loop. It strips any leading or trailing whitespace from the line using the strip() method.
  3. The function checks the line against predefined instructions (SUM, DIFF, PROD, and QUIT). If it finds a match, it performs the corresponding action on the next two lines in the file, which contain the numbers to be operated upon.
  4. If an unknown instruction is encountered, the function prints an error message.
  5. In the main function, we call process_file() with the name of the input file (instructions.txt).

Worked Example

Let's assume that our input file (instructions.txt) contains the following lines:

SUM
3.14
2.71
QUIT

When we run the program, it will output:

The sum of 3.14 and 2.71 is 5.85

Common Mistakes

1. Incorrect variable assignment

Ensure that you assign the correct variables with the appropriate user inputs or file contents. For example:

num1 = float(f.readline().strip())
num2 = float(f.readline().strip())

2. Not handling exceptions

In this simple example, we do not handle exceptions for invalid input or file errors. In real-world scenarios, it is essential to do so for various types of errors, such as division by zero, negative numbers, out-of-range values, and file I/O errors.

Practice Questions

  1. Modify the program to read instructions from a user instead of a file.
  2. Write a program that calculates the average of a list of numbers entered by the user.
  3. Create a program that sorts a list of names entered by the user alphabetically.
  4. Extend the example program to handle exceptions for division by zero, negative numbers, and out-of-range values in the input file.
  5. Refactor the example program to use functions for input validation, error handling, and calculation.
  6. Write a function that finds the greatest common divisor (GCD) of two numbers using Euclid's algorithm.
  7. Create a program that calculates the factorial of a number entered by the user.
  8. Write a function that generates Fibonacci sequence up to a given number.
  9. Modify the example program to read instructions from multiple files and perform the specified actions on each file separately.
  10. Write a program that reads a text file containing sentences and counts the frequency of each word in the text.

FAQ

Q: What happens if I encounter an unknown instruction in the input file?

A: If you encounter an unknown instruction, the program will print an error message indicating that it does not recognize the instruction. To handle this situation, you can either extend the list of predefined instructions or add a mechanism for users to define custom instructions.

Q: Why do we use the with statement when opening files in Python?

A: The with statement ensures that the file is properly closed after it has been used, even if an error occurs during its execution. This helps prevent resource leaks and makes your code more robust.

Q: How can I improve my Python programming skills?

A: Practice is key to improving your Python programming skills. Work on small projects, participate in coding challenges, and read other people's code to learn new techniques and best practices. Additionally, consider using online resources like Python Tutor for visualizing the execution of your code.

Step 5: Follow the Instructions (Python Programming) | Python | XQA Learn