Featured Posts

Start Your Journey with Linux Command Line

Image
🐧 Mastering the Linux Command Line Kali Linux Command Line Your Complete Guide: From Beginner to Confident User 35+ Essential Commands Covered with Real Examples Whether you're a developer, system administrator, or just curious about Linux, mastering the command line is an essential skill that will dramatically boost your productivity. This comprehensive guide breaks down the most critical Linux commands into logical categories with real, copy-paste examples you can try right now. We'll progress from basic file navigation to advanced system administration and network analysis, giving you a clear path to command-line proficiency. 📁 Section 1: The Core Workflow - Navigation Essentials Every Linux session follows a natural flow: figure out where you are, see what's around you, move to where you need to be, and then work with files. Let's master each step. pwd → ls ...

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)




Comments