473,657 Members | 2,415 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_inte rest_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 2303
On Sat, 25 Oct 2008 13:42:08 -0700, chemicalclothin g 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_inte rest_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, chemicalclothin g 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_inte rest_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('val ue 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(1 00)
check_range(1 2.0)
check_range(1 01.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_inte rest_rate = None
# loop until we have a value for the percentage
while per_period_inte rest_rate is None:
user_input = raw_input(promp t)
try:
per_period_inte rest_rate = make_percentage (user_input)
except ValueError:
print "Please enter a number between 0 and 100."
return per_period_inte rest_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_inte rest_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_inte rest_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
3719
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 parameters are arrays and I only want a specified number of replacements to occur.
3
5333
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
2611
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
18104
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 something like: "SELECT * FROM table WHERE name=... LIMIT 4, 10 ORDER BY id" in MySQL
4
3304
by: emily_g107 | last post by:
Hi, I need to limit results in the following query type: http://www.somewhere.com/php/sql-a.php3?server=1&db=mydatabase&table=mytable&sql_query=SELECT+Field_1%2CField_2%2CField_3%2Cidno+from+mytable+where+1+and+field_1+like+%22string%22+&sql_order=&pos=1 I found a reference that says I should be able to use LIMIT x, but I don't know where/exactly how to add that to the string. Once I know what it's supposed to look like, and can...
0
5775
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 ? SELECT ... ; ----> returns 100,000 rows
2
2833
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 by bigkey desc;
4
10767
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 limited server capability, I am also aware you can kludge the number to 40, but assume I do not want to do that). As I understand it XP Pro will support 10 simultaneous inbound (SYN) connections (5 for XP Home). My confusion arises as to what...
1
2325
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 .= '$2'; $query = preg_replace ($pattern, $replacement, $query);
3
3140
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 database in an Instance Thanks & regards sadanjan
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8740
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4173
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.