473,397 Members | 1,974 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Limit between 0 and 100

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.
Oct 25 '08 #1
4 2288
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).

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
Oct 25 '08 #2
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
Oct 26 '08 #3
On Oct 25, 1:42*pm, chemicalcloth...@temple.edu 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).

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
Oct 27 '08 #4
(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
Oct 27 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Afkamm | last post by:
Hi, :) The preg_replace function... preg_replace(pattern, replacement, subject ) How on earth do you get the limit value to work with arrays? In my code both the pattern and replacement...
3
by: CajunCoiler \(http://www.cajuncoiler.tk\) | last post by:
I've seen no reference to this in the MSDN library, so I ask here... what is the known upper limit for the RichTextbox control? And when this limit is exceeded, what error is generated?
3
by: Jay K | last post by:
Hi, I have multiple queries like this: SELECT col1, col2, col3, col4 FROM table1, table2 where table1.col1 = table2.col1 and table1.col2 = 1 ORDER BY col3 desc LIMIT 5 and
2
by: Urban | last post by:
hi, I have a question. Maybe You know the equivalent to command LIMIT from MySQL I couldn`t find something like this in MS SQL PS I try to display 10 records begining form e.g. 4 sort by id...
4
by: emily_g107 | last post by:
Hi, I need to limit results in the following query type: ...
0
by: D. Dante Lorenso | last post by:
I need to know that original number of rows that WOULD have been returned by a SELECT statement if the LIMIT / OFFSET where not present in the statement. Is there a way to get this data from PG ?...
2
by: elein | last post by:
Yes, I vacuumed. Reproduced on both 7.3.2 and 7.5. Brain dead java beans want order by clauses in views that they use. my view is: select .... from bigtable b left join lookuptable l order...
4
by: Bill | last post by:
Hi, I would be grateful if someone could clarify my rather confused ideas of the 10 connection limit on XP/2000 when its being used as a server. (I realise that XP is really a client op sys with...
1
by: lawrence k | last post by:
Want to replace the limit clause in a query, but can't get it right. What's wrong with this: $pattern = "(.*)limit (.*)"; $replacement = '$1'; $replacement .= "LIMIT $limit"; $replacement .=...
3
by: sadanjan | last post by:
Hi , Appreciate if someone can clarify if database Share Memory Limit (2 GB ) in Unix 32 bit boxes is the top limit for all the databases put together in a database or is it for each of the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.