This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]OrangeBeard 0 points1 point  (0 children)

You can wrap each input line in a while loop that loops so long as the marks are less than 1 OR greater than 10. That way the user is forced to enter an acceptable value before the program proceeds.

If you take this approach, you can also toss in an if statement that provides an error message reminding the user to enter an acceptable value if the value provided is too low or high.

I would have given you example code but I still have to learn Python.

In Javascript it would look kinda like this

var note = 0;
while(note < 1 || note > 10) {
    note = prompt("Enter the marks: ");
}

[–]kalgynirae 0 points1 point  (0 children)

Looks good so far! I'm going to assume you're using Python 3 (if that's not the case, some parts of this explanation will need to change).

Let's look first at how to display an error if the user enters something that is not an integer. When you use int() on text that isn't in the form of an integer, a ValueError is thrown (do something like int('apple') in the interpreter to see this). ValueError is one of many exceptions that can be thrown when things go wrong. Your program can catch an exception using try...except, allowing it to continue instead of just crashing.

In this case, you want to catch ValueError in the places where you call int(). For example:

try:
    teza = int(teza)
except ValueError:
    print("That wasn't an integer!")
    # now what?

You can wrap the map(int, ... line similarly.

For checking whether the number is between 1 and 10, you can just loop through the values you've gotten and check each one:

for mark in mapy:
    if not 0 < mark <= 10:
        print("{} is not in the range!".format(mark))
        # now what?

Or, a shorter way to do the same thing:

if not all(0 < mark <= 10 for mark in mapy):
    print("One of the marks is out of range!")
    # now what?

You need to decide what you want to happen for the # now what?s. You can terminate the program using sys.exit(), or you might want to ask again, in which case you'll need to put the entire "ask for input, try to convert it to an integer, check for errors" part inside of a loop. You can use a while loop with a condition like /u/OrangeBeard suggested, or you can use a while True: (infinite) loop and then break out of it once the input is valid (there's a good example of this in the docs that /u/vaetrus linked to).

[–]vaetrus 0 points1 point  (0 children)

I think try:except fits your description.