|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
|
|
Generate data entry and reporting .NET Web apps in minutes, straight from your database. Read our FREE whitepaper “Build Web 2.0 Applications Without Hand-Coding” Download now! |
|
#1
|
|||
|
|||
|
Integer input
I'm gonna accept numbers from users, and I do it like this :
if this's gonna accept number 1 until 7 only : Code:
choice = raw_input("Enter your choice : ")
if '1' <= choice <= '7':
if choice == '1':
do something
...
else:
pass
As you can see, I use raw_input() instead of input() to accept integers from user, so that it doesnt cause errors when someone accidentally key in a character. But I'm wondering, is there a faster way to do similar validation? Thanks in advance.
__________________
What can change the nature of a man? Last edited by Questioner : March 26th, 2004 at 10:38 PM. |
|
#2
|
|||
|
|||
|
Just int() the input and catch any ValueError you get from invalid int input.
|
|
#3
|
||||
|
||||
|
I don't know if this is any faster,but it will loop the raw_input if the input is out of range,or if there's a ValueError(input is a character,not a number).I'm sure there's a better way to do it,but hopefully this will give you some ideas.
Code:
answer = raw_input('Enter a number.Valid range is 1-7:')
while True:
try:
int(answer)
while int(answer) not in range(1, 7):
answer = raw_input('\nInvalid number!Valid range is 1-7:')
break
except ValueError:
answer = raw_input('\nYou must specify a number!Valid range is 1-7:')
if answer == '1':
print 'do response 1'
elif answer == '2':
print 'do response 2'
elif answer == '3':
print 'do response 3'
elif answer == '4':
print 'do response 4'
elif answer == '5':
print 'do response 5'
elif answer == '6':
print 'do response 6'
elif answer == '7':
print 'do response 7'
Code Block Generated With Py2Html
__________________
It is not important if the glass is half full or half empty.What is important,is who has been drinking from MY glass?!?!? |
|
#4
|
|||
|
|||
|
Just fyi, I wrote a command line UI module with a spinbox widget that does exactly what you're trying to do.
Here's the URL. http://www.python.org/pypi?:action=....py&version=1.4 the download link will be up soon |
|
#5
|
||||
|
||||
|
Sounds pretty sweet Mamba!
Please let us know when the download link becomes active.Thanks. |
|
#6
|
|||
|
|||
|
The link is working. Hope u like it.
|
![]() |
| Viewing: Dev Shed Forums > Programming Languages > Python Programming > Integer input |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|