Skip to content
Advertisement

Python limit input

I’m having some trouble, I want to limit the input to only integers, positive numbers, and also not zero. Now I have written these two functions and I don’t want to allow the user to put in any value. My code is not recognizing my if-statement. Only the integer/float statement. What should I do?

JavaScript

Advertisement

Answer

One of the best things about programming is that for any repetitive task on the human side, you can put the burden on the computer instead.

So, if for each pice of data you are: calling the built-in input, converting its result to integer, checking if the value is positive and non zero – the best way to go is to group these functionalities in a single function and then you just call that function – your main application then delegates the part of acquiring clean numbers, and becomes much simpler:

JavaScript

This is a bit verbose, on purpose, so it is clear that once you create a function, you can add as many simple steps as needed to do your subtask (including writing further sub-functions to be called).

Once you have that function, your program can be rewritten as:

JavaScript

And each variable is guaranteed to contain a proper positive integer, with the user being prompted until they type a suitable value, for each of them, at no cost of extra typing for each value.

As for your code: it looks all right, but for the fact that it only checks the value on a_1 for being strictly positive – so youp´d have to modify the if clause to check all the variables. (or add one if clause for each variable) – and still: it would collect all input first, and then check for negative numbers or zero.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement