Limit between 0 and 100

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sun Oct 26 02:56:44 CET 2008


On Sat, 25 Oct 2008 13:42:08 -0700, chemicalclothing wrote:

> Hi. I'm very new to Python, and so this is probably a pretty basic
> question, but I'm lost. I am looking to limit a float value to a number
> between 0 and 100 (the input is a percentage).


Before I answer that, I'm going to skip to something you said at the end 
of your post:

> P.S. I don't understand a lot of what I have there, I got most of it
> from the beginning tutorials and help sections. I have never programmed
> before, but this is for a school assignment.

Thank you for admitting this. You had made a good start, you were quite 
close to having working code.

Because this is a school assignment, you need to be careful not to pass 
off other people's work as your own. That might mean that you have to re-
write what you learn here in your own way (changing the program logic a 
little bit), or it might simply mean that you acknowledge that you 
received assistance from people on the Internet. You should check with 
your teacher about your school's policy.

 
> I currently have:
> 
> integer = int()
> running = True
> 
> while running:
>   try:
>     per_period_interest_rate = float(raw_input("Enter per-period
> interest rate, in percent: "))
>     break
>   except ValueError:
>     print "Please re-enter the per-period interest rate as a number
> between 0 and 100."
> 
> 
> I also have to make sure it is a number and not letters or anything.

Separate the parts of your logic. You need three things:

(1) You need to get input from the user repeatedly until it is valid.

(2) Valid input is an float, and not a string or anything else.

(3) Valid input is between 0 and 100.

Let's do the last one first, because it is the easiest. Since we're 
checking a value is valid, we should fail if it isn't valid, and do 
nothing if it is.

def check_range(x, min=0.0, max=100.0):
    """Fail if x is not in the range min to max inclusive."""
    if not min <= x <= max:
        raise ValueError('value out of range')


(Note: I'm "shadowing two built-ins" in the above function. If you don't 
know what that is, don't worry about it for now. I'm just mentioning it 
so I can say it isn't a problem so long as it is limited to a small 
function like the above.)

So now you can test this and see if it works:

>>> check_range(0)  # always check the end points
>>> check_range(100)
>>> check_range(12.0)
>>> check_range(101.0)  # always check data that is out of range
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in in_range
ValueError: percentage out of range


Now the second part: make sure the input is a float. Floats are 
complicated, there are lots of ways to write floats:

0.45
.45
45e-2
000.000045E4

are all valid ways of writing the same number. So instead of trying to 
work out all the ways people might write a float, we let Python do it and 
catch the error that occurs if they do something else.

Putting those two together:

def make_percentage(s):
    """Return a float between 0 and 100 from string s."""
    # Some people might include a percentage sign. Get rid of it.
    s = s.rstrip('%')
    x = float(s)
    check_range(x)
    return x

Function make_percentage() takes the user input as a string, and it does 
one of two things: it either returns a valid percentage, or it raises a 
ValueError exception to indicate an error. It can't do both at the same 
time. (By the way, there are many different exceptions, not just 
ValueError. But for now you don't care about them.)


Now let's grab the user input:

def get_input():
    prompt = "Enter per-period interest rate as a percentage: "
    per_period_interest_rate = None
    # loop until we have a value for the percentage
    while per_period_interest_rate is None:
        user_input = raw_input(prompt)
        try:
            per_period_interest_rate = make_percentage(user_input)
        except ValueError:
            print "Please enter a number between 0 and 100."
    return per_period_interest_rate


Inside the loop, if the make_percentage function raises a ValueError 
exception Python jumps to the "except" clause, and prints a message, then 
goes back to the start of the loop. This keeps going until 
per_period_interest_rate gets a valid percentage value, and then the loop 
exits (can you see why?) and the percentage is returned.


-- 
Steven



More information about the Python-list mailing list