Limit between 0 and 100

C

chemicalclothing

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).

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.

Thanks for the help.

James

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.
 
M

Marc 'BlackJack' Rintsch

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).

I currently have:

integer = int()

What's this supposed to do? I think writing it as ``integer = 0`` is a
bit simpler and more clear.
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."

You have to check for the range before you leave the loop. The
`ValueError` handling just makes sure that the input is a valid float.

The ``try``/``except`` structure can have an ``else`` branch. Maybe that
can be of use here.

Ciao,
Marc 'BlackJack' Rintsch
 
S

Steven D'Aprano

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:
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.
 
M

Matimus

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).

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.

Thanks for the help.

James

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.

You aren't very far off. You are going to need to use 'if' and '<' or
'>' to check for range though.

As in:

if x > 10:
print "x is greater than 10"

OR:

if 10 < x < 20:
print "x is between 10 and 20"

If you describe exactly what it is that you don't understand, people
here will be willing to help you to understand it. However, you will
find that people here are very unwilling to do your homework for you.

Matt
 
B

bearophileHUGS

(Sorry for the answering delay, Google groups is very slow.)

James:
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.<

You must understand what you do at school, otherwise it's just wasted
time, trust me. If you don't understand what you do, then it's better
to do something else, like fishing, or reading things you do
understand. Doing things like a robot eventually makes your brain
dumb. Do you like to become dumb?

You can't learn to program on the spot, but I suggest you to limit the
things you don't understand as much as possible.

And you can start a Python interpreter and try every single little
small thing you put into your program (and you can look for them into
the python documentation), so you can have an idea of what you are
doing. You may even try to read the notes/things your teacher may have
shown you.

What's float()?
What's raw_input()?
What's the purpose of the 'integer' variable?
What does break means, and what's its purpose there?

Maybe learning what exceptions are now it too much early, so it may be
better to not use that try-except at all, and just let your program
fail and give an error if you don't input something good. This way you
can reduce the things you don't understand. Better to show the teacher
a bare-bones program that you understand a little, than a refined
program that you don't understand at all.

Bye,
bearophile
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,608
Members
45,241
Latest member
Lisa1997

Latest Threads

Top