473,396 Members | 1,966 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,396 software developers and data experts.

Noob Question: Force input to be int?

Hello everyone!
I have a piece of code that looks like this:

if len(BuildList) 0:
print "The script found %d game directories:" % len(BuildList)
print
num = 0
for i in BuildList:
print str(num) +" " + i
num = num + 1
print
print "Select a build number from 0 to " + str(len(BuildList) - 1)
buildNum = int(raw_input('Select build #'))

while buildNum (len(BuildList) -1) or buildNum <= -1:
print
print "Error: Invalid build number!"
print "Select a build number from 0 to " + str(len(BuildList) -
1)
print
buildNum = int(raw_input('Select build: '))

The problem is with the while buildNum-loop. If the user enters a
non-numeric value in the buildNum input, the scripts throws an
exception. I need to constrict the user to ONLY use integers in the
input box. How can I solve this issue?

Jan 23 '07 #1
4 5071
I have a piece of code that looks like this:
>
if len(BuildList) 0:
print "The script found %d game directories:" % len(BuildList)
print
num = 0
for i in BuildList:
print str(num) +" " + i
num = num + 1
print
print "Select a build number from 0 to " + str(len(BuildList) - 1)
buildNum = int(raw_input('Select build #'))

while buildNum (len(BuildList) -1) or buildNum <= -1:
print
print "Error: Invalid build number!"
print "Select a build number from 0 to " + str(len(BuildList) -
1)
print
buildNum = int(raw_input('Select build: '))

The problem is with the while buildNum-loop. If the user enters a
non-numeric value in the buildNum input, the scripts throws an
exception. I need to constrict the user to ONLY use integers in the
input box. How can I solve this issue?

How about this:

while True:
try:
x = int( raw_input( 'Enter an integer: ' ) )
break
except:
pass

print 'Okay, now I have this integer: %d' % x
HTH,
Daniel
Jan 23 '07 #2
wd********@gmail.com writes:
print "Select a build number from 0 to " + str(len(BuildList) - 1)
buildNum = int(raw_input('Select build #'))

while buildNum (len(BuildList) -1) or buildNum <= -1:
print
print "Error: Invalid build number!"
print "Select a build number from 0 to " + str(len(BuildList) - 1)
print
buildNum = int(raw_input('Select build: '))

The problem is with the while buildNum-loop. If the user enters a
non-numeric value in the buildNum input, the scripts throws an
exception. I need to constrict the user to ONLY use integers in the
input box. How can I solve this issue?
You can either validate the input string before trying to convert
it ("look before you leap") or attempt conversion and handle the
exception if you get one ("it's easier to ask forgiveness than
permission"). The second pattern is generally preferable since it
means you don't duplicate input validation logic all over your
program.

The below is untested but is a partial rewrite of your code above,
intended to illustrate a few normal Python practices (I hope I haven't
introduced bugs) besides the input checking:

# just loop til you get a valid number, reading the number at the
# top of the loop. No need to read it in multiple places.
while True:
# you don't have to convert int to str for use in a print statement.
# the print statement takes care of the conversion automatically.
print "Select a build number from 0 to", len(BuildList) - 1
buildNumStr = raw_input('Select build #')

# attempt conversion to int, which might fail; and catch the
# exception if it fails
try:
buildNum = int(buildNumStr)
except ValueError:
buildNum = -1 # just treat this as an invalid value

# you can say a < x < b instead of (a < x) and (x < b)
if 0 <= buildNum < len(BuildList):
break # you've got a valid number, so exit the loop

# print error message and go back to top of loop
print
print "Error: Invalid build number!"
Jan 23 '07 #3
Ah, thank you for the respone!
I have not gotten around to test it yet, but I hope it will work! :)
-Daniel

2007-01-23 10:59:37
wd********@gmail.com wrote in message
<11*********************@k78g2000cwa.googlegroups. com>
Hello everyone!
I have a piece of code that looks like this:

if len(BuildList) 0:
print "The script found %d game directories:" % len(BuildList)
print
num = 0
for i in BuildList:
print str(num) +" " + i
num = num + 1
print
print "Select a build number from 0 to " + str(len(BuildList) -
1)
buildNum = int(raw_input('Select build #'))

while buildNum (len(BuildList) -1) or buildNum <= -1:
print
print "Error: Invalid build number!"
print "Select a build number from 0 to " +
str(len(BuildList) -
1)
print
buildNum = int(raw_input('Select build: '))

The problem is with the while buildNum-loop. If the user enters a
non-numeric value in the buildNum input, the scripts throws an
exception. I need to constrict the user to ONLY use integers in the
input box. How can I solve this issue?
Jan 23 '07 #4


On 23 Sty, 10:59, wd.jons...@gmail.com wrote:
Hello everyone!
I have a piece of code that looks like this:

if len(BuildList) 0:
print "The script found %d game directories:" % len(BuildList)
print
num = 0
for i in BuildList:
print str(num) +" " + i
num = num + 1
print
print "Select a build number from 0 to " + str(len(BuildList) - 1)
buildNum = int(raw_input('Select build #'))

while buildNum (len(BuildList) -1) or buildNum <= -1:
print
print "Error: Invalid build number!"
print "Select a build number from 0 to " + str(len(BuildList) -
1)
print
buildNum = int(raw_input('Select build: '))

The problem is with the while buildNum-loop. If the user enters a
non-numeric value in the buildNum input, the scripts throws an
exception. I need to constrict the user to ONLY use integers in the
input box. How can I solve this issue?
Also if you would like to try mentioned approach 'Look before you
leap', this code should be quite clear:

buildNumber = ('foo', 'bar')
n = len(buildNumber)
loop = True
while loop:
input = raw_input('select a build number from 0 to %d: ' % (n-1))
if input.isdigit():
ch = int(input)
loop = not ch in range(n) # if ch is NOT in range of [0, n),
then it is ok to loop
if loop:
print 'Error! Invalid build number'
print 'Choice: %d' % ch

In fact I don't know if it applies to python, but in conventional
languages it is a bad habit to use exceptions for every simple test as
it takes time to jump around code. So, correct me please.

Jan 24 '07 #5

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

Similar topics

4
by: HolaGoogle | last post by:
hi there, i've 2 questions for you guys.... 1: is there any way to "force" a session_onend(), session timeout or at least call my logout method when a user leaves the application window without...
3
by: We need more power captain | last post by:
Hi, I know less than a noob, I've been asked to do some compiles in VC++ 6 without knowing too much at all. (I'm a COBOL program normally so this is all too much for me) I open VC++6, open...
8
by: Ivan Shevanski | last post by:
Alright heres another noob question for everyone. Alright, say I have a menu like this. print "1. . .Start" print "2. . .End" choice1 = raw_input("> ") and then I had this to determine what...
2
by: What nickname do you want? | last post by:
I want to provide secured acces to a MySQL database. This is what I've done. Firstly the relevant pages are in a folder to which Apache requires password authentication. Then I have an HTML page...
5
by: A Programmer | last post by:
Ok, we have just delved full force in to VS 05 and I am fairly comfortable with the layout. But I think I have run into my first gotcha. I setup a web application doesn't produce a /bin with a...
8
by: sore eyes | last post by:
Hi I just downloaded the free Watcom compiler and am having a little trouble with File IO http://www.openwatcom.org/index.php/Download I downloaded the following example, commented out the...
19
by: Zach Heath | last post by:
I'm just starting C and haven't done programming for a few years...could you guys please take a look at this? Thanks for your time! I have an input file that looks like: 1.5 2.5 Bob, Joe...
3
by: johnmcmadeup | last post by:
How can I make it so that, if the user inputs 2 numbers with a space in between , I can get both numbers(instead of just the first number, which happens when I try cin>>var;)?
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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...
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.