Featured Posts

Start Your Journey with Linux Command Line

Image
Start Your Journey with the Linux Command Line: A Comprehensive Guide Whether you are a software developer, system administrator, analytics engineer, or cybersecurity enthusiast, mastering the Linux command line (terminal) is one of the single most effective skills you can acquire. While graphical user interfaces (GUIs) offer visual convenience, the command line interface (CLI) delivers unmatched speed, fine-grained system control, and seamless automation capabilities. Linux Command Line This tutorial breaks down more than 35 core Linux commands into structured, practical modules complete with real-world examples, flags, and command-chaining techniques. By building muscle memory around these fundamentals, you will elevate your daily technical workflow from basic navigation to advanced command orchestration. Why Learn the Command Line? The Linux CLI is not merely a legacy tool—it remains the foundation of modern cloud architecture, server maintenance, DevOps pipelines, and enterp...

Python LAB 2.8.1.4 Reading ints safely

 Reading ints safely

Reading ints safely
Reading ints safely

The Challenge

  • improving the student's skills in defining functions;
  • using exceptions in order to provide a safe input environment.

Scenario

Your task is to write a function able to input integer values and to check if they are within a specified range.

LAB sandbox
LAB Sandbox

The function should:

accept three arguments: a prompt, a low acceptable limit, and a high acceptable limit;

if the user enters a string that is not an integer value, the function should emit the message Error: wrong input, and ask the user to input the value again;

if the user enters a number which falls outside the specified range, the function should emit the message Error: the value is not within permitted range (min..max) and ask the user to input the value again;

if the input value is valid, return it as a result.

Test data

Test your code carefully.

This is how the function should react to the user's input:

Enter a number from -10 to 10: 100

Error: the value is not within permitted range (-10..10)

Enter a number from -10 to 10: asd

Error: wrong input

Enter number from -10 to 10: 1

The number is: 1

Solution:

def read_int(prompt, min, max):

    ok = False
    while not ok:     #---> True
        try:    
            value = int(input(prompt))
            ok = True
        except ValueError:
            print("Error: Wrong Input")
        if ok:
            ok = value >= min and value <= max
        if not ok:
            print("Error: The value is not within range(" + str(min) + ".." + str(max) + ")")
    return value
v = read_int("Enter a number from -10 to 10: ", -10, 10)
print("The number is:", v)




Building a Safe Input Function

LAB 2.8.1.4 "Reading ints safely" asks you to write a function named read_int that accepts three arguments: a prompt string, a low limit, and a high limit. The function must repeatedly ask the user for input until a valid integer within the specified range is supplied. This lab ties together two skills: defining your own functions and using exceptions to create a safe input environment that never crashes on bad data.

The function works by looping until a valid value is found. A boolean flag, here named ok, starts as False. Inside a while not ok loop, the program attempts to convert the user's input to an integer with int(input(prompt)). If that conversion succeeds, the flag is set to True; if it fails with a ValueError, the except block prints "Error: Wrong Input" and the loop continues so the user can try again.

Validating the Range

Once a number has been successfully converted, the function must still check that it lies within the allowed bounds. The ok flag is then updated with ok = value >= min and value <= max. If the value falls outside the range, this expression becomes False, and the code prints a message like "Error: The value is not within range(min..max)" before looping again. Only when the value is both an integer and within range does the flag remain True, allowing the function to return the value.

This combination of a try/except for the type check and a conditional test for the range check makes the function robust to every kind of invalid input. Whether the user types letters, symbols, or a number that is simply too large, the program keeps prompting rather than terminating. The pattern of a validation loop driven by a boolean flag is reusable anywhere you need trustworthy numeric input.

Key Takeaways

  • The read_int function takes a prompt, a low limit, and a high limit as arguments.
  • A while not ok loop drives the repeated prompting until valid input arrives.
  • Calling int(input(prompt)) inside a try block catches a ValueError for non-integer input.
  • The range check value >= min and value <= max rejects numbers outside the allowed bounds.
  • Messages such as "Error: Wrong Input" tell the user what went wrong so they can retry.

Frequently Asked Questions

What exception is raised when the user types text instead of a number?

Calling int() on a string that is not a valid integer raises a ValueError. Catching that exception lets the function print a message and ask again instead of crashing.

Why use a boolean flag rather than exiting the loop with break?

The flag keeps the loop condition simple and lets the same outer loop handle both conversion errors and range errors. Each error just resets the flag to False so the loop repeats.

How are the min and max limits applied?

After a successful conversion, the expression value >= min and value <= max determines whether the number is within bounds. If not, the program prints a range error and loops again.

What does the function return?

Once a value is both a valid integer and within the specified range, the function returns that number so the caller can use it, for example by printing "The number is:" followed by the value.

Comments

Popular Posts

PROJECT MAVEN | The Architecture of Algorithmic Warfare

Python 3.2.1.14 LAB: Essentials of the while loop

Data Analysis Roadmap 2026: From Excel Lover to Python-Powered Analyst

Python for Windows Beginners: Build Your First Automated Workflow in 10 Minutes

Python 4.3.1.10 LAB: Converting fuel consumption